[英]Difference between adding properties to constructor or prototype
我看到了两种向类添加属性的方法。
我想知道它们之间的区别。 这是代码和JsBin
var show = function() {
console.log('Show started..');
// Adding properties in constructor
this.properties = {
name: 'Testing javascript'
};
};
show.prototype.getName = function() {
console.log(this.properties.name);
};
// Adding properties to prototype
show.prototype.properties = {
name: 'Testing prototype'
};
var myShow = new show();
myShow.getName();
对于所有实例,原型成员都是共享的:
var Person=function(name){
this.obj.name=name;
};
Person.prototype.obj={name:"Default"};
var ben = new Person("Ben");
var leo = new Person("Leo");
console.log(ben.obj.name);//logs Leo
在上面的代码中,ben和leo都共享obj
成员。 行为(函数)通常放在原型上,因为它们不会因实例而改变。 在原型上具有此功能将节省初始化和内存,因为无论在原型上创建该函数的实例有多少次,它都只会存在一次。
在构造函数中使用this.someProp=...
声明的成员是特定于实例的。
有关构造函数和原型的更多信息,请查看此答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.