Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中实现继承?_Javascript_Inheritance_Prototype - Fatal编程技术网

如何在JavaScript中实现继承?

如何在JavaScript中实现继承?,javascript,inheritance,prototype,Javascript,Inheritance,Prototype,我希望构造函数文件继承构造函数视图。我已经读到需要一个临时构造函数new F(),但是父类和子类原型在我的代码中一起被修改: function View() {}; function Paper() {}; View.prototype = { location: { "city": "UK" } } function F() {}; F.prototype = View.prototype; Paper.prototype = new F(); Pape

我希望构造函数
文件
继承构造函数
视图
。我已经读到需要一个临时构造函数
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.prototype.location.city = "US";
我发现
视图的原型也被修改了!:

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

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

正如您所发现的,JS中的继承很棘手。也许有比我更聪明的人可以在技术细节上告诉我们为什么,但是一个可能的解决方案是使用框架,这是一个很好的解决方案

编辑:我已经重新构造了原始代码,以适应迪安·爱德华的框架。

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

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的问题。