在函数构造函数中设置原型 [英] Setting prototypes inside function constructor

查看:110
本文介绍了在函数构造函数中设置原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var a = function(){
    this.sayFoo = function(){
        console.log('foo');
    };
}

var b = function(){
    console.log(this.prototype); //undefined
    this.sayBar = function(){
        console.log('bar');
    };
}

b.prototype = new a();

var bInst = new b();

bInst.sayFoo();
bInst.sayBar();

console.log(b.prototype); //a {sayFoo: function}

http://jsfiddle.net/KbBny/1/

如何添加 sayBar 到函数构造函数中的 b 原型?

How do I add sayBar to the b prototype inside the function constructor?

是否 b.prototype = new a(); 覆盖原型,或用 a合并 b 的?

Does b.prototype = new a(); overwrite the prototype, or merge b's with a's?

推荐答案


b .prototype = new a(); 覆盖原型,或者将b与a合并?

Does b.prototype = new a(); overwrite the prototype, or merge b's with a's?

它确实用新的 a 实例覆盖它;没有合并(例如,您需要更新 b.prototype.constructor 属性)。这就是为什么你在这行之后将所有属性添加到 b.prototype 的原因。但是,实际上您不想创建实例,只需正确设置原型链:

It does overwrite it with a new a instance; nothing is merged (for example you'd need to update the b.prototype.constructor property). That's why you do add all properties to b.prototype after this line. However, actually you don't want to create an instance, but just set up the prototype chain correctly:

b.prototype = Object.create(a.prototype);




如何在函数构造函数中的b原型中添加sayBar?

How do I add sayBar to the b prototype inside the function constructor?

你不应该把它添加到原型中,因为它不是原型(共享)方法 - 它是特定于每个实例的一个实例(至少它应该是,否则你会把它放在 a.prototype 然后它被上面覆盖线)。要在所有 b 实例上获取实例方法,请使用

You should not add it to the prototype, as it is not a prototype (shared) method - it's instance-specific to every a instance (at least it should be, otherwise you would put it on a.prototype and then it gets covered by above line). To get the instance method on all b instances as well, you use

var b = function(){
    a.call(this); // invoke the `a` constructor on this instance
};

这篇关于在函数构造函数中设置原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆