在另一个问题中,用户指出该new关键字使用起来很危险,并提出了一种不使用的对象创建解决方案new.我不相信这是真的,主要是因为我使用了Prototype,Scriptaculous和其他优秀的JavaScript库,并且每个人都使用了new关键字.
尽管如此,昨天我在YUI剧院观看道格拉斯·克罗克福德的演讲,他说的完全一样,他new在代码中不再使用关键字(Crockford on JavaScript - Act III:Function the Ultimate - 50:23分钟).
使用new关键字"不好" 吗?使用它有哪些优缺点?
这是我想做的事情:
function a() {
// ...
}
function b() {
// Some magic, return a new object.
}
var c = b();
c instanceof b // -> true
c instanceof a // -> true
b instanceof a // -> true
Run Code Online (Sandbox Code Playgroud)
可能吗?我可以通过挂钩到它的原型链b来成为一个a容易的实例a但是我必须这样做new b(),这就是我想要避免的.我想要的是什么?
更新:我觉得有可能明智地使用b.__proto__ = a.prototype.我下班后要去做更多的实验.
更新2:下面是你可以得到的最接近的,这对我来说已经足够了.谢谢所有有趣的答案.
function a() {
// ...
}
function b() {
if (!(this instanceof arguments.callee)) {
return new arguments.callee();
}
}
b.__proto__ = a.prototype …Run Code Online (Sandbox Code Playgroud)