美文网首页Js方法延伸
javascript深入理解系列(三)——constructor

javascript深入理解系列(三)——constructor

作者: 悦者生存 | 来源:发表于2020-01-03 12:58 被阅读0次

prototype对象有一个构造函数,默认指向prototype对象所在的构造函数

function Person(name,age){
            this.name=name;
            this.age=age;
        }
        var xiaoming=new Person("小明",10);
        console.log(Person.prototype.constructor==Person);

因为constructor属性定义在prototype上面,所以可以被构造函数的所有实例对象使用

console.log(xiaoming.constructor===Person);

xiaoming本身并没有constructor属性,而是继承的其原型链上的constructor

constructor的作用是可以知道实例对象的构造函数是谁

constructor属性表示原型对象与构造函数之间的关联关系,如果修改了原型对象,一般会同时修改constructor属性,防止引用的时候出错。

function Person(name,age){
            this.name=name;
            this.age=age;
        }
        var xiaoming=new Person("小明",10);
        Person.prototype={
            say:function(){
                console.log("说话");
            }
        }
        console.log(Person.prototype.constructor==Person);//输出false

因为Person.prototype指向了普通对象,普通对象的prototype.constructor指向Object

console.log(Person.prototype.constructor==Object);//输出true

所以,修改原型对象时,一般要同时修改constructor属性的指向。

// 坏的写法
C.prototype = {
  method1: function (...) { ... },
  // ...
};

// 好的写法
C.prototype = {
  constructor: C,
  method1: function (...) { ... },
  // ...
};

// 更好的写法
C.prototype.method1 = function (...) { ... };

相关文章

网友评论

    本文标题:javascript深入理解系列(三)——constructor

    本文链接:https://www.haomeiwen.com/subject/xtbuwftx.html