Jos*_*eph 13 javascript closures
我用这个样本回答了一个关于闭包的问题:
function Constructor() {
var privateProperty = 'private';
var privateMethod = function(){
alert('called from public method');
};
return {
publicProperty: 'im public',
publicMethod: function(){
alert('called from public method');
},
getter: privateMethod
}
}
var myObj = new Constructor();
//public
var pubProp = myObj.publicProperty;
myObj.publicMethod();
myObj.getter();
//private - will cause errors
myObj.privateProperty
myObj.privateMethod
Run Code Online (Sandbox Code Playgroud)
一位用户评论我的回答说:
此外,如果您的函数显式返回一个对象,那么使用new调用它并不是一个好习惯,因为这会产生误导 - 如果使用new,您希望结果是Constructor的一个实例
我通常使用new创建对象.但为什么这不是一个好的做法?似乎使用new而不使用new返回相同的东西.从闭包创建对象的正确方法是什么?
Ry-*_*Ry- 11
不,这不是一回事.使用时考虑instanceof:
function C1() {
return {};
}
function C2() {
}
var c1 = new C1();
var c2 = new C2();
alert(c1 instanceof C1); // false; wha...?
alert(c2 instanceof C2); // true, as you'd expect.
Run Code Online (Sandbox Code Playgroud)
因此,通过分配this,可能有一个安全措施,以防止被遗忘的news 创建它们.
function Constructor() {
var privateProperty = 'private';
var privateMethod = function() {
alert('Called from private method');
};
this.publicProperty = "I'm public!";
this.publicMethod = function() {
alert('Called from public method');
};
this.getter = privateMethod;
}
Run Code Online (Sandbox Code Playgroud)
更好的是,尽可能使用原型:
function Constructor() {
var privateProperty = 'private';
var privateMethod = function() {
alert('Called from private method');
};
this.getter = privateMethod;
}
Constructor.prototype.publicProperty = "I'm public!";
Constructor.prototype.publicMethod = function() {
alert('Called from public method');
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3330 次 |
| 最近记录: |