2
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

b.prototype = new a();会覆盖原型,还是将b's 与a's合并?

4

3 回答 3

2

您没有使用正确的继承模式。

采用:

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

在您的情况下,您正在执行简单的覆盖,您没有正确建立继承。Object.create是 ES5,但你可以用这个来填充:

对象.create

if (!Object.create) {
    Object.create = function (o) {
        if (arguments.length > 1) {
            throw new Error('Object.create implementation only accepts the first parameter.');
        }
        function F() {}
        F.prototype = o;
        return new F();
    };
}

访问原型

您无法访问prototype定义块的内部。你有一个this参考。

var b = function() {
    a.call(this);
    b.prototype.doSomething = function() {console.log("b");}; 
};
b.prototype = Object.create(a.prototype);

演示

于 2013-05-16T08:34:49.760 回答
1

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

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

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

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

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

var b = function(){
    a.call(this); // invoke the `a` constructor on this instance
};
于 2013-05-16T08:41:55.457 回答
0

内部构造函数的原型排序

您可以使用包装功能。我相信它们在 Javascript 中被称为装饰器函数。在哪里设置原型。然后,当您将该装饰器函数用作构造函数时,您不必单独设置原型。可以这么说,它被设置在一个充当构造函数的函数中。

function Human(name, lastname, age) {
  function _human(name, lastname, age) {
    this.name = name;
    this.lastname = lastname;
    this.age = age;
  }
  _human.prototype.sayName = function() {
    console.log(this.name + " " + this.lastname);
  }
  var temp = new _human(name, lastname, age);
  return temp;
}

然后,您只需执行以下操作:

var person = new Human("John", "Doe", 25);
console.log(person);
person.sayName();
于 2018-12-02T03:12:55.227 回答