'new'키워드가 자바 스크립트에서 작동하는 방식을 정리하려고합니다. 그러나 그것은 이상한 행동을합니다. 내가 노드에서이 코드를 실행하면
는 :Javascript 하위 함수의 새 키워드
var testing = function() {
self = this;
this.abc = 'abc';
console.log(this); // ====> 1
var subMethod = function() {
console.log(this); // =====> 2
console.log(self === this); // ====> 3
};
//subMethod.apply(this);
subMethod();
};
test = new testing();
// test = testing(); // ===> *4
을 console.log (자기 ===이) 나 false를 제공합니다. nr 1의 'this'는 {abc : 'abc'}이며 하위 메소드의 'this'는 전역 'this'객체입니다. 아무도 나 에게이 행동에 대한 설명을 줄 수 있습니까?
subMethod.apply (this)로 실행하면 console.log (self === this)가 true ({abc : 'abc'})
새 키워드 (* 4)없이 실행하면 ' 이 변수는 예상대로 글로벌 'this'와 동일하며 console.log (self === this)도 true입니다.
왜 'this'가 'new'키워드로 실행될 때 글로벌 'this'와 같은 submethod에 있습니까?
this.subMethod = function ....을 적용 할 때. 그렇다면이 범위는 예상대로입니다 {abc : 'abc', subMethod : [Function]} – Christian
관련 : http://stackoverflow.com/questions/111102 * 명시 적으로 'new'에 대해 논의하지는 않지만 실제로는 없습니다. 특별한 점은 기대했던 것과 똑같습니다. 클로저는 까다로운 비트 다. – blgt