对象的Javascript继承
如果我们有一个父对象,如:对象的Javascript继承,javascript,inheritance,Javascript,Inheritance,如果我们有一个父对象,如: var Animal = function(name) { this.name = name; return this; } 我们使用原型如下: Animal.prototype.Dog = function(){ console.log(this.name); } 这真是太好了。 但我试图实现的是继承子对象中的父属性,如 Animal.prototype.Child = { Dog : function(){ co
var Animal = function(name) {
this.name = name;
return this;
}
我们使用原型
如下:
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);
}
}
但是这里的包含窗口
对象,而不是动物
。也
Animal.prototype.Child = {
Animal: new Animal('Puppy'),
Dog : function(){
console.log(this.Animal.name);
}
}
不是这里的选项。您的继承链看起来不正确。您将创建两个不同的构造函数。每个构造函数创建一个对象。继承部分是建立原型链并在子类中调用“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, //<---
...
}
如果我们调用不带点符号的函数,它将无法工作。同样,这只取决于函数的调用方式。这行不通:
var fn = obj.method;
fn(); // won't work
fn.call(obj); //=> will work, we pass the context explicitly
我真的不明白你想用Animal.prototype.Child={Dog:..}
实现什么。这不是继承通常看起来的样子。看一看。
var fn = obj.method;
fn(); // won't work
fn.call(obj); //=> will work, we pass the context explicitly