. this
은 을 말합니다. 이후 리터럴이 계산되는 동안 평가 중에 this
은 부모 범위를 나타냅니다. 함수에 객체 구성을 래핑하여 this
이 현재 범위 (즉, 함수의 범위)를 참조하는지 확인할 수 있습니다. 뭔가 같이 : 함수의 범위 내에서
var person = function(){
this.name = 'John';
this.__test__ = (function(){alert(this.name);}());
return this;
}();
또는 사용 변수 :
var person = function(){
var _name = 'John'
,_test = (function(){alert(_name);}());
return { name: _name, __test__: _test };
}();
또는 더 일반적인 공장 기능에 물건을 포장 : 마지막으로
function objFactory(obj){
var nwObj = {};
for (var l in obj){
if (obj.hasOwnProperty(l)){
if (obj[l] instanceof Function && /^auto_/i.test(l)){
nwObj[l.replace(/^auto_/i,'')] = obj[l].call(nwObj);
}
else {
nwObj[l] = obj[l];
}
}
}
return nwObj;
}
//=> usage
var person = objFactory(
{ name: '',
auto_name: function(){
this.name='John';
return this.name;
}
}
);
alert(person.name); //=> John
그리고 (모든 사람이 동의 할 것이다 이)에서로드 핸들러를 만들 수 있습니다 Object.prototype
:
Object.prototype.load = function(){
for (var l in this){
if (this.hasOwnProperty(l)
&& this[l] instanceof Function
&& /^auto_/i.test(l)) {
this[l].call(this);
delete this[l];
}
}
return this;
}
//=> usage
var person = {
name: '',
auto_name: function(){this.name='John';}
}.load();
alert(person.name); //=> John
,
나를 위해 정의되었습니다. 어떤 설정을 사용하고 있습니까? – Blender
코드의 의미는 무엇입니까 ??? – gdoron
@gdoron 내 업데이트를 참조하십시오. – user310291