在另一个问题中,用户指出该new关键字使用起来很危险,并提出了一种不使用的对象创建解决方案new.我不相信这是真的,主要是因为我使用了Prototype,Scriptaculous和其他优秀的JavaScript库,并且每个人都使用了new关键字.
尽管如此,昨天我在YUI剧院观看道格拉斯·克罗克福德的演讲,他说的完全一样,他new在代码中不再使用关键字(Crockford on JavaScript - Act III:Function the Ultimate - 50:23分钟).
使用new关键字"不好" 吗?使用它有哪些优缺点?
我最近Object.create()在JavaScript中偶然发现了这个方法,并试图推断它与创建一个对象的新实例有什么不同new SomeFunction(),当你想要使用另一个时.
请考虑以下示例:
var test = {
val: 1,
func: function() {
return this.val;
}
};
var testA = Object.create(test);
testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2
console.log('other test');
var otherTest = function() {
this.val = 1;
this.func = function() {
return this.val;
};
};
var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1
console.log(otherTestB.val); // 2
console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2Run Code Online (Sandbox Code Playgroud)
请注意,在两种情况下都观察到相同的行为.在我看来,这两种情况之间的主要区别是:
Object.create()实际使用的对象实际上形成了新对象的原型,而在new …