JavaScript中的原型 [英] Prototypes in JavaScript
本文介绍了JavaScript中的原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JavaScript中你可以用很多不同的方式做同样的事情。
In the JavaScript the same thing you can do in many different ways.
考虑一下例子:
1:
function Circle(radius) {
return {
"r" : radius,
"area" : function(){
return Circle.pi * this.r * this.r;
}
}
}
Circle.pi = 3.14159;
var a = Circle(10);
alert(a.area());
2:
function Circle(radius) {
this.r = radius;
}
Circle.pi = 3.14159;
Circle.prototype.area = function(){
return Circle.pi * this.r * this.r;
}
var a = new Circle(10);
alert(a.area());
第二个比第一个好,因为我们没有定义相同的函数 area 对于 Circle 的任何实例。
The second is better than first because we dont define the same function area for any instance of the Circle.
但我们可以考虑
3:
But lets consider 3:
function Circle(radius) {
return {
"r" : radius,
"area" : Circle.area
}
}
Circle.pi = 3.14159;
Circle.area = function(){
return Circle.pi * this.r * this.r;
}
var a = Circle(10);
alert(a.area());
有没有理由更喜欢第二种而不是第三种?或者我误解了一些东西?
Is there any reason to prefer second style instead of third? Or I misunderstood something at all?
推荐答案
我肯定会选择示例2.示例1或3都没有充分利用JavaScript的面向对象的功能,因为:
I would definitely go with example 2. Neither example 1 or 3 make good use of JavaScript's object-oriented features because:
- 你在每个实例中复制方法定义。
- 通过返回一个新对象而不是使用
这个
,你失去了类的身份,即你不能再做像一样的支票圈
。 - 由于不使用原型,您放弃了继承的可能性。
- You duplicate method definitions in each instance.
- By returning a new object instead of using
this
, you lose the identity of the class, i.e. you can no longer do checks likea instanceof Circle
. - You give up the possibility of inheritance since you do not use prototypes.
这篇关于JavaScript中的原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文