admin管理员组文章数量:1365850
I'm learning JavaScript, and I can't understand why you'd make methods that aren't 'privileged,' that is, that aren't defined in the constructor but rather the class' prototype.
I understand the idea of encapsulation and all, but you never encapsulate parts of a class from the rest of it in most of the OO world.
I'm learning JavaScript, and I can't understand why you'd make methods that aren't 'privileged,' that is, that aren't defined in the constructor but rather the class' prototype.
I understand the idea of encapsulation and all, but you never encapsulate parts of a class from the rest of it in most of the OO world.
Share Improve this question asked Jun 18, 2010 at 1:30 Aaron YodaikenAaron Yodaiken 19.6k33 gold badges108 silver badges187 bronze badges1 Answer
Reset to default 18When a function is defined in a constructor, a new instance of that function is created each time the constructor is called. It also has access to private variables.
var myClass = function() {
// private variable
var mySecret = Math.random();
// public member
this.name = "Fred";
// privileged function (created each time)
this.sayHello = function() {
return 'Hello my name is ' + this.name;
// function also has access to mySecret variable
};
}
When a function is defined on the prototype, the function is created only once and the single instance of that function is shared.
var myClass = function() {
// private variable
var mySecret = Math.random();
// public member
this.name = "Fred";
}
// public function (created once)
myClass.prototype.sayHello = function() {
return 'Hello my name is ' + this.name;
// function has NO access to mySecret variable
};
So defining a function on the prototype produces less objects which can give you better performance. On the other hand, public methods do not have access to private variables. Further examples and reasoning are available here: http://www.crockford./javascript/private.html
本文标签: javascriptwhy make nonprivileged methodsStack Overflow
版权声明:本文标题:javascript - why make non-privileged methods? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743779081a2537512.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论