Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

javascript - What is difference between define function by prototype and class property?

Follow my code,
Apple is define function by prototype.
Banana is define function by class property.

var Apple = function(){}
Apple.prototype.say = function(){
    console.debug('HelloWorld');
}
var Banana = function(){
    this.say = function(){
        console.debug('HelloWorld');
    }
}

var a = new Apple();
var b = new Banana();

a.say();
b.say();

Are these difference ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you create more than one instance of Apple, you will still only have only one instance of say() in memory. However, when you create more than one instance of Banana, you will end up creating lots of instances of the say() function.

That's why prototypes save memory. You also avoid the processing cost of creating and assigning the say() function.

Also, if you change the parent object's properties, if the child does not replace that property, changes are visible from the child.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...