如何在JavaScript中实现继承

How do you get inheritance working within JavaScript?

本文关键字:实现 继承 JavaScript      更新时间:2023-09-26

我希望构造函数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

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

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

编辑:我已经重组了原始代码,以适应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

我希望这能有所帮助!