为什么在js中使用原型方法?当我为两者创建一个新对象时,他们会做同样的事情吗?
function Rectangle(w, h) {
this.width = w;
this.height = h;
this.area = function( ) { return this. width * this. height; }
}
Run Code Online (Sandbox Code Playgroud)
要么
Rectangle.prototype.area = function(){
return this.width * this.height
}
Run Code Online (Sandbox Code Playgroud)
有很大的不同.虽然这两个(如你定义他们)会当你打电话给你同样的返回值.area()上一个Rectangle实例,在你的第一个例子中,每一个Rectangle对象获取其自身的副本area功能.在第二种情况下,它们共享一个副本(这样可以提高内存效率).
哪个是首选取决于您正在解决的问题.在您的示例中,几乎可以肯定地使用原型.这通常是你想要的方式.但是,如果你有一个Foo构造函数,并且永远不会有很多Foo实例,并且你认为Foo拥有真正的私有数据至关重要,那么你可以使用私有成员习语:
function Foo() {
var trulyPrivateVariable;
this.getVar = function() {
return trulyPrivateVariable;
};
this.putVar = function(v) {
// Presumably some logic or checks here
trulyPrivateVariable = v;
};
}
Run Code Online (Sandbox Code Playgroud)
这种模式利用了一个事实,即功能是关闭在trulyPrivateVariable构造函数中的局部变量.
但是,请记住,对于每个实例,这些函数都是重复的,因此这仅适用于审核.
值得注意的是,这些并非相互排斥.你可以按照Foo上面的说法:
Foo.prototype.doSomething = function() {
// Do something completely unrelated -- note that code here
// does not have access to `trulyPrivateVariable`, although it
// will have access to `this.getVar()` and `this.putVar()`
// (assuming it's called in the normal way).
};
Run Code Online (Sandbox Code Playgroud)
...这样你就可以获得尽可能多的重用,只需将绝对需要访问的部分trulyPrivateVariable放在构造函数内部,它们将被复制.
偏离主题:为了简洁,我在上面使用了匿名函数(正如你所做的那样),但我不是生产代码中的粉丝.
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |