function Demo() {
this.show1 = function() { alert(1) }
}
Demo.prototype.show2 = function() { alert(2) }
var d = new Demo
d.show1()
d.show2()
show1 and show2 can both alert number.
Is there any difference between these two?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, if you initialize that method inside the constructor, e.g. (
this.method = function () {};), all of your 1000 object instances will have a function object as own property.Well, it’s the most lightweight way to go, let’s say you have a method in the prototype of certain constructor, and you create 1000 object instances, all those objects will have your method in their prototype chain, and all of them will refer to only one function object.
In the second case, only those objects, which get created after the
Demo.prototype.show2 = function(){alert(2)}will get the code. 🙂Example
Your code
Other Case