这个比。原型 [英] this Vs. prototype
问题描述
将方法area定义为this的属性而不是prototype的区别是什么?
Whats the difference between defining the method "area" as a property of "this" instead of "prototype"?
//console.clear()
function Rectangle(w, h)
{
this.width = w;
this.height = h;
this.area = function( ) { return this.width * this.height; }
}
var r = new Rectangle(2, 3);
var a = r.area( );
//console.log(a)
function Square(s)
{
this.side= s;
}
Square.prototype.area = function(){return this.side * this.side; }
var r = new Square(2);
var a = r.area( );
//console.log(a)
JavaScript -
部分中的权威指南
第9章第1部分
,作者说在原型对象中定义方法area是有益的,但他的解释并不是真的可以理解:
In JavaScript - The definitive guide
in the section Prototypes and Inheritance
of Chapter 9 , part 1
, the author says that defining the method "area" inside the prototype object is beneficial, but his explanation wasn't really understandable:
..每个矩形
对象的区域总是指同一个
函数(有人可能改变它,
当然,但你通常打算使用
方法
对于
的方法,使用常规的
属性是低效的,这些方法是由同一个类的所有对象
共享的(即所有
使用相同的
构造函数创建的对象。
"..the area of every single Rectangle object always refers to the same function (someone might change it, of course, but you usually intend the methods of an object to be constant). It is inefficient to use regular properties for methods that are intended to be shared by all objects of the same class (that is, all objects created with the same constructor)."
我知道这个问题几乎就像这个,但是它不是。
I know this question almost looks like this one, but it is not.
推荐答案
用定义一个函数= = {({}}
倾向于创建所谓的闭包,其中函数可以访问定义它的函数的局部变量。当你说 this.fn = function(){...}
时,每个对象都会获得一个函数实例(以及一个新的闭包)。这通常用于在Javascript中创建私有变量,但需要付出代价:每个函数(在每个对象中)都是不同的,并占用更多内存。
Defining a function with whatever = function() { ... }
tends to create what's called a "closure", where the function can access local variables of the function that defines it. When you say this.fn = function() { ... }
, each object gets an instance of the function (and a new closure). This is often used to create "private" variables in Javascript, but comes with a cost: each function (in each object) is distinct, and takes up more memory.
当你说 Rectangle.prototype.fn = function(){...}
时,所有 Rectangle $共享该函数的一个实例C $ C>秒。这样可以节省内存,并且可以最大程度地减少处理严重关闭的浏览器中的一些内存泄漏。如果您不需要私有成员或其他此类访问定义函数的局部变量,通常是一个更好的主意。
When you say Rectangle.prototype.fn = function() { ... }
, one instance of the function is shared by all Rectangle
s. This saves memory, and can minimize some memory leaks in browsers that handle closures badly. If you don't need "private" members, or other such access to the defining function's local variables, it's usually a better idea.
这篇关于这个比。原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!