原型链、prototype、_proto_–基础概念篇

1.prototype与_proto_

每个对象都有_proto_属性,每个函数都有prototype属性,他们的关系如下:

    function Person(){

    }
    var man = new Person();
    console.log(Person.prototype == man._proto_);

每一个函数的prototype对象都是一个最基本的object对象.每个对象都有一个 __proto__ 属性来实现对原型的 隐式引用
函数的prototype的作用是:使用这个函数作为构造函数创建的对象会具有函数的prototype的所有属性和方法.例子如下:

    var fn = function(){

    };
    fn.prototype.study = function(){
        console.log('studying');
    };
    fn.prototype.type = 'function';
    var foo = new fn();

    foo.study(); // studying
    console.log(foo.type); // function
    // for(var key in fn.prototype){
        // console.log(foo[key]);
    // }

可以看到用fn构造函数创建的对象foo具有fn的prototype的所有属性和方法.
而原型链由_proto_进行维护

2.constructor

每一个函数都有一个constructor属性.每个实例都有constructor属性默认调用原型对象的constructor属性。任何一个prototype对象都有一个constructor属性,指向它的构造函数.
通常情况下一个函数的constructor属性就是生成它的函数,即创建自身的构造函数。

    function Person(){

    }
    var man = new Person();
    console.log(man.constructor); // function Person

注意:通常情况下!每个实例都有constructor属性默认调用原型对象的constructor属性。每个实例的constructor属性不一定指向构造函数。

3.prototype和constructor合用

prototype和constructor合用会产生什么样有趣的化学效果呢?

    var fn = function(){
        console.log('fdfd');
    };
    var foo = new fn();
    console.log(fn.prototype); // Object
    console.log(foo.prototype); // undefined 使用new创建的对象无prototype属性
    console.log(fn.constructor); // Function
    console.log(fn.prototype.constructor === fn); // true
    console.log(foo.constructor === fn); // true

prototype是实现面向对象的重要机制.当用new创建一个对象时,prototype对象的属性将自动赋给所创建的对象,用new创建的对象没有prototype属性

每个函数都有constructor与prototype属性。函数的prototype属性指向prototype对象,而prototype对象有一个constructor属性,指回函数

由图可以得知:实例有构造函数创建,但跟构造函数没有直接关系,其_proto_属性指向了构造函数的prototype对象,而构造函数的prototype对象的constructor属性指向了构造函数,构造函数的prototype属性指向了构造函数的prototype对象,即实例和原型通过构造函数产生了联系.

参考文章:
a).JS函数浅析之constructor、prototype属性

此条目发表在JavaScript分类目录。将固定链接加入收藏夹。

发表评论

邮箱地址不会被公开。 必填项已用*标注