javascript - 在构造函数中分配原型(prototype)

标签 javascript

我有这个代码:

var MyClass = function(b) {
    this.a = b;
    this.getA = function() {
        return that.a;
    }
}

var SecondClass = function(b) {
    this.prototype = new MyClass(b);
    this.getB = function() {
        return 6;
    }
}

var a = new SecondClass(2);
console.log(a.getA());

输出告诉我 a 没有名为 getA() 的方法

我假设在 SecondClass 的构造函数中执行 this.prototype = new MyClass() 会导致它从 MyClass 继承方法?

我确信有更好的方法可以做到这一点,但我正在尝试了解原型(prototype)关键字的行为。

最佳答案

prototype构造函数的特殊属性,而不是实例

当你用new Func()调用构造函数时,引擎会创建一个继承自Func.prototype的新对象,然后设置this 在构造函数中引用新对象。

因此,除了 this.prototype 只是一个普通属性之外,在赋值发生时继承已经发生。

因为您没有为 MyClass.prototype 分配任何方法,所以您不必在此处对原型(prototype)继承做任何事情。您所要做的就是使用 .call [MDN]MyClass 应用于新创建的实例。 :

var SecondClass = function(b) {
    MyClass.call(this, b);
    this.getB = function() {
        return 6;
    }
};

但是,您应该add all methods that are shared by instances to the prototype然后让 SecondClass 的每个实例都继承自它。这是完整设置的样子:

var MyClass = function(b) {
    this.a = b;
}
MyClass.prototype.getA = function() {
    return this.a;
};

var SecondClass = function(b) {
    // call parent constructor (like 'super()' in other languages)
    MyClass.call(this, b);
}
// Setup inheritance - add 'MyClass.prototype' to the prototype chain
SecondClass.prototype = Object.create(MyClass.prototype);
SecondClass.prototype.getB = function() {
    return 6;
};

var a = new SecondClass(2);
console.log(a.getA());

所有这些 will become easier in ES6 .

关于javascript - 在构造函数中分配原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16173901/

相关文章:

javascript - GPL 许可证如何限制商业 Web 应用程序?

JavaScript 下拉菜单

java - 如何为单个引擎实例设置 java-8 Nashorn javascript 引擎选项

javascript - 在 AngularJS 上使用欧元符号格式化输入

javascript - 如何在PHP中通过base64验证大小和图像扩展名?

Javascript 与 C# 在 ASP.NET 4.5 MVC 中动态更改元素类/id

javascript - 在 php 中使用下拉菜单排序和检索数据

javascript - 正则表达式 - 匹配之前不存在的字符

javascript - 使用 Anime.js 进行 SVG 线条动画

javascript - 迭代多个 Meteor 集合