JavaScript原型继承这个代码与另一个代码有什么不同?

时间:2015-04-16 10:57:51

标签: javascript prototypal-inheritance

我有一个关于JS原型设计的问题:

如果我有以下构造函数:

function Person(name) {
     if (!(this instanceof Person))
         return new Person(name);
     this.name = name;
}
Person.prototype.sayHello = function() {
    console.log("Hello from " + this.name);
}

这里我有一个方法sayHello绑定到Person的原型,这个内存效率更高:

function Person(name) {
     if (!(this instanceof Person))
         return new Person(name);
     this.name = name;
     this.sayHello = function() {
        console.log("Hello from " + this.name);
     }
}

只是一瞥:

原型人:

enter image description here

非原型人:

enter image description here

如您所见,sayHello 功能的引用将在所有创建的人之间“共享”,而不是仅为每个实例化人员创建新功能。 this在{strong> 特定人员调用sayHello()后,只要在sayHello()上下文中使用function Person(name) { if (!(this instanceof Person)) return new Person(name); this.name = name; this.__proto__.sayHello = function() { console.log("Hello from " + this.name); } } ,就会变异指向正确的人。

现在,另一个变种:

Person.prototype.sayHello

输出与sayHello的输出相同,这意味着Person.prototype === bob.__proto__ // true在不同的人之间共享。

但这两种方法有区别吗?我想不,因为:

Person.prototype.*

那么真的,当一个人应该使用前者(构造函数外的this.__proto__.*)而不是后者(构造函数中的{{1}})?

1 个答案:

答案 0 :(得分:2)

扩展Felix的评论。

版本如下:

this.__proto__.sayHello = function() {
    console.log("Hello from " + this.name);
}

不应该被使用。

每次调用封闭构造函数时,上面的代码也会运行,创建该匿名函数的 new 副本,并覆盖当前在prototype中保存的引用

碰巧持有对该函数的前一个实例的引用的任何代码将继续指向该旧版本。

在内存效率方面,它与编写this.sayHello = function(...)非常相似,因为没有一个实例实际上共享该函数的同一副本。在代码效率方面,它可以说更糟糕(虽然相当于使用Person.prototype.sayHello = ...),因为每次调用都需要提升原型链。