如何使用 Crockfords 的 Object.create() (Javascript) 访问我祖先的重写方法
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
var o1 = {};
o1.init = function(){
alert('o1');
};
var o2 = Object.create(o1);
o2.init = function(){
// how would I call my ancessors init()?
alert('o2');
};
o2.init();
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
var o1 = {};
o1.init = function(){
alert('o1');
};
var o2 = Object.create(o1);
o2.init = function(){
// how would I call my ancessors init()?
alert('o2');
};
o2.init();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
JavaScript 函数是对象,有两个有用的方法来调用该函数:
您可以使用其中之一来调用父实现,显式传递
this
作为scope
参数,以便在父实现中,this
引用子对象:这将发出警报:
o1: Two
和o2: Two
。JavaScript functions are objects and have two useful methods to invoke the function:
You can use one of these to call the parent implementation, explicitely passing
this
as thescope
parameter, so that in the parent implementation,this
refers to the child object:This will alert:
o1: Two
ando2: Two
.也许这过于简化了您想要完成的任务...将 o1.init() 放在 o2 init 函数中会起作用吗?
出于好奇,“ancessors”是“ancestor's”的拼写错误,还是“ancessors”在这里有特定的含义?您是指 o2 的“父”对象吗?
Maybe this is oversimplifying what you’re trying to accomplish ... would placing o1.init() in the o2 init function work?
Out of curiosity, was "ancessors" a spelling error for "ancestor’s" or does "ancessors" mean something specific here? Did you mean o2’s "parent" object?
在支持它的浏览器中,您可以使用
Object.getPrototypeOf
函数,如下所示:这将获取
o2
(o1
) 的原型,并且将其init
方法应用于此 (o2
),就像其他语言中的super.init()
一样。更新:
Object.getPrototypeOf
函数可以这样实现:在此链接上找到:http ://ejohn.org/blog/objectgetprototypeof/
In browsers that support it, you could use the
Object.getPrototypeOf
function, like this:This would get the prototype of
o2
(o1
) and apply itsinit
method to this (o2
), just like asuper.init()
in other languages.UPDATE:
The
Object.getPrototypeOf
function could be implemented like this:Found on this link: http://ejohn.org/blog/objectgetprototypeof/