在函数构造函数中设置原型

时间:2013-05-16 08:33:38

标签: javascript prototype

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();会覆盖原型,还是将ba合并?

3 个答案:

答案 0 :(得分:2)

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

使用:

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

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

<强>的Object.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);

<强> DEMO

答案 1 :(得分:1)

  

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

合并

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

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

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

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

b

答案 2 :(得分:0)

原型构造器内部的排序

您可以使用包装功能。我相信它们在Javascript中称为decoratorfunctions。在哪里设置原型。然后,当您使用该decorator函数作为构造函数时,就不必分别设置原型。可以这么说,它将设置在充当构造函数的函数中。

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();