JS进阶

JS进阶(一)

一些铺垫:

     每一个对象都有__proto__属性,主要用来继承,每一个函数都有prototype属性,上面挂载属性、方法,注意一下函数里面的prototype.constructor属性,跟对象、字符串等的constructor不一样。

        函数里面的prototype.constructor是指向函数的一个引用,而对象等的constructor输出的话可以看到是ƒ Object() { [native code] }这样的形式,这个是js底层的一些设计。

        我们实现继承时将constructor纠正,其实只是更规范一点,能够看到这个函数的引用,相当于一个提示,避免造成误导,constructor属性没什么实际性作用,只有很少的机会我们会利用他,比如会利用他给增加一些方法,如下:
function fun(){};
var res = new fun();
res.constructor.prototype.add = function(){}
//因为res.constructor是指向fun的,所以我们可以给fun增加方法通过这种方式。

typeof instanceof

typeof "123"//string
typeof true//boolean
typeof 1//number
typeof undefined//undefined
typeof new Data()//object
typeof [1,2]//object
typeof function(){}//function
typeof null//object

       从上边的栗子可以看出来,typeof可以准确识别,string,number,boolean,undefined,function,但是无法区别数组、null、object、date,其中null是由于历史原因遗留下来的,返回object。所以我们判断 这几种的时候需要注意是否能区分。想要准确识别的话,可以像这样:

Object.prototype.toString.call([1,2,3])//"[object Array]"

       通过对结果正则匹配,可以准确得到数据类型,具体代码,可以去另一篇《我的JS库》里面找,getParamType方法,不再一一列举,下面介绍instanceof:

function fun(){}
var res = new fun();
res instanceof fun//true
Object.getPrototypeOf(res) === fun.prototype//true

      在使用instanceof时,相当于执行了 Object.getPrototypeOf(res) === fun.prototype,是在判断构造函数的prototype是不是在实例的原型链上,有点绕,关键看代码理解。

猜你喜欢

转载自blog.csdn.net/qq_39771254/article/details/80973789
今日推荐