gpt4 book ai didi

JavaScript 继承

转载 作者:行者123 更新时间:2023-11-28 16:40:39 27 4
gpt4 key购买 nike

目前我正在尝试几种不同的 Javascript 继承方法。我有以下代码:

(“借用”自 http://www.kevlindev.com/tutorials/javascript/inheritance/index.htm )

KV = {};

KV.extend = function(subClass, baseClass) {
function inheritance() {}
inheritance.prototype = baseClass.prototype;

subClass.prototype = new inheritance();
subClass.prototype.constructor = subClass;
subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;
}

function GridView() {
var _ownerElement;
}

GridView.prototype.getOwnerElement = function() {

return this._ownerElement;
}

GridView.prototype.setOwnerElement = function(ownerElement) {
this._ownerElement = ownerElement;
}

GridView.prototype.initialize = function() {
this.setOwnerElement('test');
}


function StreetGridView(dataURL, ownerElement) {
StreetGridView.baseConstructor.call(this);

StreetGridView.superClass.initialize();

StreetGridView.superClass.setOwnerElement(ownerElement);


}

// subclass StreetGridView
KV.extend(StreetGridView, GridView);

现在,当我创建 StreetGridView 的实例时,我可以毫无问题地调用 getOwnerElement() 。一切都按预期进行。

但是

当我创建另一个实例时,对实例 2 所做的任何更改都会反射(reflect)在实例 1 中。

我知道这是使用原型(prototype)作为共享实例信息的主要问题。今天早上我绞尽脑汁,但想知道是否有人可以为我指明正确的方向!

谢谢

最佳答案

the_drow:

我在上面留下了关于使用您的解决方案调用 super 构造函数两次的评论 - 但让您继续执行inheritPrototype 感到有点遗憾。首先,感谢 Nicholas Zakas,因为这是我对他的书《Professional JavaScript for Web Developers》第二版(第 181 页)的解释:

function inheritPrototype(sub,sup) {
var proto = object(sup.prototype);// you'll need an object create method ;)
proto.constructor = sub;
sub.prototype = proto;
}

现在替换您的:

StreetGridView.prototype = new GridView();

与,

StreetGridView.prototype = inheritPrototype(StreetGridView,GridView);

并且您只调用了 GridView 构造函数一次!但您会注意到对象方法。你需要类似的东西:

function object(o) {
function F(){};
F.prototype = o;
return new F();
}

如果您读过道格拉斯·克罗克福德 (Douglas Crockford) 的任何著作,那么您一定看过这本!

无耻插件: 这个东西很难理解,这正是我写一篇关于 TDD JavaScript 的文章的确切原因,整个第二部分有一堆继承模式的单元测试。我正在专门研究 Zakas 和 Crockford 有关对象创建和继承的书籍。您不必阅读我的文章(目前为 Open Office .odt 格式),但您可能会做比下载我的代码并在 2 分钟内阅读它更糟糕的事情!这是链接: My Free Book

关于JavaScript 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/892467/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com