开发者

Javascript prototype question

while i was reading about prototype in javascript, I had开发者_运维问答 a question.

Let's say I have the following functions and objects

Function #1:
function Rectangle(w,h){
    this.width = w;
    this.height = h;
    this.area = function(){return this.width * this.height}
}

var object1 = new Rectangle(10,5);
var object11 = new Rectangle(5,5);


Function #2:
function Rectangle(w,h){
    this.width = w;
    this.height = h;
}

Rectangle.prototype.area = function(){ return this.width * this.height; }

var object2 = new Rectangle(10,5);
var object22 = new Rectangle(5,5);

As far as I understand object2 and object22 use less memory than object1 and object11 because function #2 uses prototype.

is this correct?


Yes that is theoretically correct, because Function 1 creates a unique function for area each time it is called, whereas objects created with Function 2 all reference a common function.

However, each JavaScript engine will have different optimisations, and it is possible to optimise Function 1 so that internally each object points to the same function, until one of them is modified (this is necessary because as far as the language is concerned, each function is unique, and attaching a property to one should not affect the others).

There is very little documentation on the web about the specific optimisations performed by each browser, but here are a couple of references that seem to point towards some form of closure optimisation:

  • https://groups.google.com/group/v8-users/browse_thread/thread/3a4eeecb8569a251?pli=1
  • https://developer.mozilla.org/En/SpiderMonkey/Internals/Functions


It's "correct" for the classic view of Javascript. I think modern javascript compilers may alleviate the wastefulness of the first approach, but if you are creating lots of small objects that could share a function on the prototype, I still consider it good style to do so.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜