javascript - 如何让继承在 JavaScript 中起作用?

标签 javascript inheritance prototype

我希望构造函数 Paper 继承构造函数 View。我读到需要有一个临时构造函数 new F(),但是在我的代码中父类与子类原型(prototype)一起被修改:

function View() {};
function Paper() {};

View.prototype = {
    location: {
        "city": "UK"
    }
}


function F() {};

F.prototype = View.prototype;
Paper.prototype = new F();
Paper.prototype.constructor = Paper;

所以当我尝试修改Paper 的原型(prototype)时:

Paper.prototype.location.city = "US";

我发现 View 的原型(prototype)也被修改了!:

var view = new View();
console.log(view.location); //US! not UK

那么我的代码有什么问题呢?如何在不影响父级的情况下覆盖原型(prototype)?

最佳答案

正如您所发现的,JS 中的继承很棘手。也许比我聪明的人可以告诉我们关于为什么的技术细节,但一个可能的解决方案是使用 very tiny Base.js框架,由 Dead Edwards 提供.

编辑:我重构了原始代码以适应 Dean Edward 的框架。

一旦掌握了语法,继承就会正常工作。这是基于您的代码的可能解决方案:

var View = Base.extend({
    constructor: function(location) {
        if (location) {
            this.location = location;
        }
    },

    location: "UK",

    getLocation: function() {
        return this.location;
    }
});

并扩展它:

var Paper = View.extend({
    location: "US"
});

并测试它:

var view = new View();
alert("The current location of the view is: " + view.getLocation());
var paper = new Paper();
alert("The location of the paper is: " + paper.getLocation());
alert("The current location of the view is: " + view.getLocation());

或者,同样的结果可以通过:

var Paper = View.extend();

和测试:

var view = new View();
alert("The current location of the view is: " + view.getLocation());
var paper = new Paper("US");
alert("The location of the paper is: " + paper.getLocation());
alert("The current location of the view is: " + view.getLocation());

两者都会产生三个警报:

The current location of the view is: UK
The location of the paper is: US
The current location of the view is: UK

希望对您有所帮助!

关于javascript - 如何让继承在 JavaScript 中起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17861240/

相关文章:

javascript - IE 7 中重新加载页面会清除输入字段中的文本

javascript - jQuery Tree 问题 - 添加第一个 child li

c++ - 如何向结构添加新成员

javascript - JavaScript 中令人困惑的原型(prototype)行为

javascript - 重定义构造函数原型(prototype)后,对象构造函数指向原始构造函数而不是prototype.constructor

Javascript对象属性数组,无法访问值

javascript - npm 错误!无效版本 : "1"

c++ - 调用父类(super class)方法运算符==

java - 为什么 Java 中的 "protected"修饰符允许访问同一包中的其他类?

javascript - 通过原型(prototype)方法设置对象的属性