原型
首先,我必须告诉你,我不是专家,你可能会在这个主题上找到更好(完整)的答案。
这3种方法之间的主要区别在于原型。方法1 [使用函数]
可以让你绑定原型对象,这些对象不会与其他对象共享。
你可以向Apple
对象以及Object
对象添加原型方法。例如:
//init
Object.prototype.hello = 'Hello';
Apple.prototype.world = ' World';
//Method 1
alert(apple.hello + apple.world); //Hello World
//Method 2
alert(apple.hello + apple.world); //Helloundefined
//Method 3
alert(apple.hello + apple.world); //Helloundefined
可重用性
如果你想要多个相同对象的实例,没有第一种方法会很麻烦。比如你想要两个不同的苹果,你需要复制/粘贴并更改属性(除了第一种方法)。
var macintosh = new Apple('macintosh');
var otherApple = new Apple('Heisenberg')
var macintosh = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
var otherApple = {
type: "I'm not good with apple's name",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
var macintosh = new (function(type) {
this.type = type;
this.color = "red";
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
};
})('macintosh');
var otherApple = new (function(type) {
this.type = type;
this.color = "red";
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
};
})('Still not better');
变量作用域
在方法1和方法3中,您可以拥有局部变量。这些元素在对象外部不可访问。
当您在对象内部具有事件处理程序函数时,这是非常有用的。在这些函数中,您会失去this
引用。幸运的是,您可以将其保存在局部变量中。以timeout
为例,不要使用.bind()
之类的东西来欺骗自己:
var apple = {
getMe : 'YES!',
setTimer : function(){
setTimeout(this.goGetHim, 500);
},
goGetHim : function(){
alert(apple.getMe);
}
}
yourinitfn(){
var self = this
this.getMe : 'YES!',
this.setTimer : function(){
setTimeout(this.goGetHim, 500);
},
this.goGetHim : function(){
alert(self.getMe);
}
}
apple.self;
鉴别
最后一件我能想到的是鉴别。基本上,你可以很容易地通过方法#1知道这个物体是一个苹果:
alert(apple instanceof Object);
alert(apple instanceof Apple);
alert(apple instanceof Object);
alert(apple instanceof Apple);
alert(apple instanceof Object);
alert(apple instanceof Apple);
必须有其他优势
如果有人能在这些主题上找到其他优势,我将不胜感激:
- 内存
- 性能
- 可读性
- 编程语言兼容性(例如:通过 JSON 将对象转换为 PHP)
- 其他我想不到的东西...
最后说明
我从未使用过也永远不会使用单例函数来创建对象。我曾经在某个地方读到过(现在找不到参考资料了),使用 new function
是一种不好的做法并且会严重影响性能。请注意,我可能在这里是错误的...