函数与对象千丝万缕的联系:原型链

万物皆为对象,万事皆为行为

JavaScript中所有变量都可以当作对象使用,null 和 undefined除外。
JavaScript不包含传统的类继承模型,而是使用 prototype 原型模型。

那些年我们搬过的砖头

我们自诩为搬砖工,平常常常可能遇到以下这些砖头:
    var a = undefined, b = null, c = false, d = 1, e = 'uncle', f = [2, 3], g = new Date(), h = function () {},i = {'name':'shawn'};
    console.log("**************基本类型**************");
    console.log(typeof a);//未定义 undefined
    console.log(typeof b);//空指针 null
    console.log(typeof c);//布尔值 boolean
    console.log(typeof d);//数值 number
    console.log(typeof e);//字符串 string
    console.log(typeof f);//数组 object
    console.log(typeof g);//内置对象 object
    console.log(typeof h);//自定义函数 object
    console.log(typeof i);//自定义函数 object
实际上,原生类型都似乎有包装类的,我们查看下他们的类型:
    console.log(typeof Boolean); //"function"
    console.log(typeof Number);//"function"
    console.log(typeof String);//"function"
    console.log(typeof Array);//"function"
    console.log(typeof Function); //"function"
    console.log(typeof Object);//"function"

    所以,对象由构造函数生成,构造函数本身也是对象

妖怪,现出你的原型吧

所有的函数自带了prototype属性,prototype自带了constructor函数;
所有对象(undefined、null除外)都有内置的[[prototype]]属性,它指向父类的prototype;
    console.log("**************小喽啰原形**************");
    console.log(Boolean.prototype); //Boolean函数
    console.log(Number.prototype);//Number函数
    console.log(String.prototype);////String函数
    console.log(Array.prototype);//Array函数

    console.log("**************大Boss原形**************");
    console.log(Function.prototype); //{} 空对象
    console.log(Object.prototype); //null 空指针
    function Thing(name) {
        this.name = name;
    }
    var thing = new Thing('web');
    console.log(Thing.prototype === thing.__proto__) ;//true
    console.log(Thing.prototype.constructor === Thing);//true

 


你祖坟,刨根问底

new关键词的作用就是完成实例与父类原型之间关系的串接,并创建一个新的对象;
instanceof关键词的作用,是判断__proto__链条,所指向是否父类的原型:

    console.log(thing instanceof Thing); //=> true
    console.log(thing instanceof Object); //=> true
    console.log(thing instanceof Function); //=> false

    console.log(thing.__proto__ ==  Thing.prototype); //=> true
    console.log(thing.__proto__.__proto__  ==  Object.prototype); //=> true
    console.log(thing.__proto__.__proto__  ==  Function.prototype); //=> false
    console.log(thing.__proto__.__proto__.__proto__   ==  null); //=> true

用武之地

类继承:传递原型链,调用构造函数
属性查找:for-in语句与hasOwnProperty函数配合
 
posted @ 2016-08-08 17:25  肖大叔的小巫  阅读(173)  评论(0编辑  收藏  举报