2

我希望构造函数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's 的原型也被修改了!:

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

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

4

1 回答 1

0

正如您所发现的,JS 中的继承很棘手。也许比我更聪明的人可以在技术细节上告诉我们为什么,但一个可能的解决方案是使用非常小的 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

我希望这有帮助!

于 2013-07-25T14:50:13.313 回答