如何在JavaScript中使用继承?

时间:2013-07-25 14:42:14

标签: javascript inheritance prototype

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

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

1 个答案:

答案 0 :(得分:0)

正如您所发现的那样,

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

我希望这有帮助!