对象的Javascript继承

时间:2014-01-30 06:29:45

标签: javascript inheritance

如果我们有一个父对象,如:

var Animal = function(name) {
    this.name = name;
    return this;
}

我们使用prototype之类的:

Animal.prototype.Dog = function(){
    console.log(this.name);
}

这很有效。 但我想要实现的是继承子对象中的父属性,如

Animal.prototype.Child = {
    Dog : function(){
        console.log(this.name);
    }
}

我们怎么做到这一点。我试图找到它两天。我也试过了:

Animal.prototype.Child = {
    that:this,
    Dog : function(){
        console.log(this.that.name);
    }
}

但此处that包含window对象而非Animal。还

Animal.prototype.Child = {
    Animal: new Animal('Puppy'),
    Dog : function(){
        console.log(this.Animal.name);
    }
}

这里是一个选项。

1 个答案:

答案 0 :(得分:2)

您的继承链看起来不正确。你将创建两个不同的构造函数。每个构造函数都创建一个对象。继承部分是设置原型链并在子类中调用“super”。换句话说,你会这样做:

// Constructor for animals
function Animal(name) {
  this.name = name;
  // no need to return this
  // as a constructor returns the instance
  // when using the `new` keyword
}

// Public methods of all animals
Animal.prototype.say = function(){
  // implement
};

// Constructor for dogs
function Dog(name) {
  // Call "super", inherit parent properties
  Animal.apply(this, arguments);
}

// Public methods of dogs
Dog.prototype.fetch = function(){
  // implement
};

// Setup prototype inheritance chain
// and save a reference to our constructor
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

即使您的继承看起来不正确,但这是一种常见的误解:

Animal.prototype.Child = {
  that: this, //<---
  ...
}

this是函数的上下文,值取决于函数的调用方式。上面代码中的thiswindow;注意没有功能。

在下面的代码中,thisobj

var obj = {
  prop: 'foo', 
  method: function() {
    return this.prop;
  }
};

obj.method();
//^ logs "foo" because we are using dot notation (`obj` is the receiver)

如果我们调用没有点表示法的函数,它将无法工作。同样,this仅取决于函数的调用方式。这不起作用:

var fn = obj.method;
fn(); // won't work
fn.call(obj); //=> will work, we pass the context explicitly