window.name = "window";
object = {
name: "object",
method: function() {
var self = this;
var nestedMethod = function() {
console.log(self.name); // or object.name without declaring self
}
nestedMethod();
}
}
object.method(); // print 'object'
저장 개체의 범위 - 또는 객체 자체를 사용!
우리가 만든 익명의 모든 기능은 전역 범위에 적용됩니까?
아니, 모든 익명 함수, 그들은 특정 this
호출하지 않으면 스코프 (전역 객체에 바인딩 모든 기능이 apply
및 call
은, 아래의 예를 참조 참조 그들의 범위를 잃을하지)! 이런 식으로 호출 것
window.name = "window";
object = {
name: "object",
method: function() {
var nestedMethod = function() {
console.log(this.name);
}
nestedMethod.call(this); //change the this arg in the current object scope
// when you call this function with .call(this) you are changing the value of the nestedMethod's this to the current this, which is object
}
}
object.method(); // print 'object'
당신은 개체의 이름을 사용하여 시도 할 수 object.name''있도록 : 당신이 전화를 작동하기위한 수동으로 컨텍스트를 정의 할
call
(또는apply
)를 사용할 수 있습니다. – elclanrsno. 모든 함수는 속성으로 객체에 바인딩되지 않는 한 기본적으로 전역 범위로 이동합니다 ... – dandavis
@dandavis는 정말 정확하지 않습니다. 함수는 본질적으로 모든 범위를 ""수행하지 않습니다. 'this'의 값은 함수를 호출 할 때마다 상황에 따라 결정됩니다. – Pointy