在另一个问题中,用户指出该new关键字使用起来很危险,并提出了一种不使用的对象创建解决方案new.我不相信这是真的,主要是因为我使用了Prototype,Scriptaculous和其他优秀的JavaScript库,并且每个人都使用了new关键字.
尽管如此,昨天我在YUI剧院观看道格拉斯·克罗克福德的演讲,他说的完全一样,他new在代码中不再使用关键字(Crockford on JavaScript - Act III:Function the Ultimate - 50:23分钟).
使用new关键字"不好" 吗?使用它有哪些优缺点?
所以我有这两个例子,来自javascript.info:
例1:
var animal = {
eat: function() {
alert( "I'm full" )
this.full = true
}
}
var rabbit = {
jump: function() { /* something */ }
}
rabbit.__proto__ = animal
rabbit.eat()
Run Code Online (Sandbox Code Playgroud)
例2:
function Hamster() { }
Hamster.prototype = {
food: [],
found: function(something) {
this.food.push(something)
}
}
// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()
speedy.found("apple")
speedy.found("orange")
alert(speedy.food.length) // 2
alert(lazy.food.length) // 2 (!??)
Run Code Online (Sandbox Code Playgroud)
从示例2开始:当代码到达时 …
以下代码的作用如下:
WeatherWidget.prototype = new Widget;
Run Code Online (Sandbox Code Playgroud)
哪里Widget是构造函数,我想用新函数扩展Widget'类' WeatherWidget.
什么是new关键字在那里做什么以及如果被遗漏会发生什么?