JavaScript原型的好处 [英] The Benefits of JavaScript Prototype
本文介绍了JavaScript原型的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在想JavaScript的原型性质及其好处,并且归结为以下列表:
I've been wondering about JavaScript's prototypal nature, and the benefits of it, and have come down to the following list :
1)继承
cat.prototype = animal
2)内存效率
a.prototype.b = function() {}
var a1 = new a();
var a2 = new a();
然后a1.b和a2.b基本上是同一个对象,其中:
Then a1.b and a2.b are essentially the same object, where as :
var a = function() {
this.b = function() {};
}
var a1 = new a();
var a2 = new a();
a1.b和a2.b将是不同的函数对象并占用更多内存。
a1.b and a2.b would be different function objects and take up more memory.
3)将方法/字段添加到已创建的多个野外对象中。
var a = function() {}
var a1 = new a();
var a2 = new a();
a.prototype.b = function() {}
a1.b();
a2.b();
所以问题是,这些是正确的吗?
So the question is, are these correct?
......还有其他任何我错过的好处吗?
... and are there any other benefits I've missed?
干杯!
推荐答案
这些都是正确的。
当然,也有缺点:
没有关闭
function a() {
var ival = 0;
this.start = function(){ ival = setInterval(function(){ }, 300); }
this.finish = function(){ clearTimeout(ival); }
}
比较:
function a() {
this.ival = 0;
}
a.prototype.start = function(){ this.ival = setInterval(function(){ }, 300); }
a.prototype.finish = function(){ clearTimeout(this.ival); }
这篇关于JavaScript原型的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文