【问题标题】:How do you get inheritance working within JavaScript?如何在 JavaScript 中实现继承?
【发布时间】:2013-07-25 12:52:12
【问题描述】:

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

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

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


function F() {};

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

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

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

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

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

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

【问题讨论】:

标签: javascript inheritance prototype


【解决方案1】:

正如您所发现的,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

我希望这会有所帮助!

【讨论】:

  • 能否请您调整框架以适应 OP 的问题,而不是从链接页面复制示例?我担心它不会起作用。
  • @Bergi 完成,虽然我要到今天下午才能自己测试它。
  • 请在某个时候测试一下,我相信这仍然会显示问题。
  • @Bergi 已修复!希望这至少部分回答了 OP 的问题。
猜你喜欢
  • 1970-01-01
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
  • 2023-03-25
  • 2015-02-08
相关资源
最近更新 更多