对象的Javascript继承

标签 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);
    }
}

在这里不是一个选项。

最佳答案

您的继承链看起来不对。您将创建两个不同的构造函数。每个构造函数创建一个对象。继承部分是建立原型(prototype)链并在子类中调用“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 是函数的上下文,值取决于函数的调用方式。上面代码中的this就是window;请注意,这里没有任何功能。

在下面的代码中,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

关于对象的Javascript继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21449354/

相关文章:

javascript - react 数组映射中的设置值不起作用

javascript - Angular 2 - 绑定(bind)数字数组以选择选项

C++ 和抽象类中的继承

c# - 统一 : Handling inheritance with JSONUtility. ToJSON

javascript - PostgreSQL 物化 View 在刷新时阻塞读取

javascript - 清除vue 3中的输入文件

javascript - 在 JavaScript 中,我可以阻止 onmouseup 事件被触发,并将其替换为我自己的事件吗?

html - <h1>没有从其容器继承font-weight

C++ 继承和共享/非共享函数

c++ - 返回基类对象中的派生对象指针