함수를 생성하면 해당 함수에 사용할 수 있는 this
的关键字(在幕后),该关键字链接到函数运行的对象。换句话说,this
라는 범위가 생성되지만 이는 함수가 속성이나 메서드로 갖는 객체에 대한 참조입니다.
이전 기사의 cody
개체를 살펴보겠습니다.
예: Sample98.html
으아악getGender
함수 내에서 getGender
函数内部,我们如何在 cody
对象本身上使用点表示法 (cody.gender
) 访问 gender
属性。可以使用 this
重写来访问 cody
对象,因为 this
指向 cody
개체 자체의 점 표기법(cody.gender
)을 사용하여 gender
속성에 액세스하는 방법을 확인하세요.
개체를 가리키므로
재정의를 사용하여 개체에 액세스할 수 있습니다. this.gender
中使用的 this
으아악
this
的主题可能会令人困惑,但事实并非如此。请记住,一般来说, this
在函数内部使用来引用该函数所包含的对象,而不是函数本身(例外情况包括使用 new
关键字或 call()
和 应用()
this
arguments
和发送到函数的任何参数相反,this
키워드
인수
및 함수에 전송된 모든 인수와 달리 this
는 호출/활성화 개체의 키워드(속성이 아님)입니다.
this
myObject
对象被赋予一个名为 sayFoo 的属性,该属性指向 sayFoo
函数。当从全局范围调用 sayFoo
函数时,this
引用 window
对象。当作为 myObject 的方法调用时,this
指的是 myObject
모든 함수에 전달되는
myObject
有一个名为 foo
다음 코드 예제의 myObject
개체에는 sayFoo
함수를 가리키는 sayFoo라는 속성이 할당됩니다. sayFoo
함수가 전역 범위에서 호출되면
개체를 참조합니다. myObject의 메소드로 호출될 때
는myObject
를 참조합니다.
this
的值基于调用该函数的上下文。考虑 myObject.sayFoo
和 sayFoo
都指向相同的函数。但是,根据调用 sayFoo()
的位置(上下文),this
window
예: Sample100.html
분명히
의 값은 함수가 호출되는 상황에 따라 달라집니다.myObject.sayFoo
와 sayFoo
가 모두 동일한 함수를 가리킨다는 점을 고려하세요. 하지만 (컨텍스트) sayFoo()
가 호출되는 위치에 따라 의 값이 달라집니다.
도움이 된다면 헤더 개체를 명시적으로 사용하는 동일한 코드를 참조하세요(this
和 arguments
).
this
함수를 전달하거나 함수에 대해 여러 참조를 만들 때 함수를 호출하는 상황에 따라 this의 값이 변경된다는 점을 명심하세요. this
在一个包含在另一个函数中的函数内部使用时会发生什么。坏消息是在 ECMA 3 中,this
迷失了方向并引用了头对象(浏览器中的 window
및 인수
를 제외한 모든 변수는 어휘 범위를 존중합니다
func2
和 func3
中的 this
迷失了方向,并且不是指向 myObject
다른 함수 내에 포함된 함수 내에서
를 사용하면 어떻게 되는지 궁금하실 것입니다. 나쁜 소식은 ECMA 3에서
가 길을 잃고 함수가 정의된 객체 대신 헤더 객체(브라우저의 객체)를 참조했다는 것입니다. foo.func1
时会发生什么。当在 foo.func1
(函数中的函数)内部调用匿名函数时,匿名函数内部的 this
func2
및 func3
의 가 손실되어 myObject
가 아닌 헤드 개체를 가리킵니다.
예: Sample102.htmlthis
으아악
foo.func1
에 전달하면 어떤 일이 발생하는지 생각해 보세요. foo.func1
(함수 내의 함수) 내에서 익명 함수가 호출되면 익명 함수 내의
this
值不会丢失,您可以简单地使用作用域链在父函数中保留对 this
的引用。以下示例演示了如何使用名为 that
예: Sample103.html
이제 절대 잊지 마세요. 호스트 함수가 다른 함수 내에 래핑되거나 다른 함수의 컨텍스트에서 호출될 때
값은 항상 헤더 객체에 대한 참조가 됩니다(이 역시 ECMAScript 5에서 수정되었습니다). 🎜 🎜 🎜스코프 체인을 사용하여 중첩 함수 문제 해결🎜 🎜 🎜 값이 손실되지 않도록 하려면 범위 체인을 사용하여 상위 함수에서 🎜에 대한 참조를 유지하면 됩니다. 다음 예에서는that
이라는 변수를 사용하고 해당 범위를 활용하여 함수 컨텍스트를 더 잘 추적할 수 있는 방법을 보여줍니다. 🎜
🎜예: Sample104.html🎜
<!DOCTYPE html><html lang="en"><body><script> var myObject = { myProperty: 'I can see the light', myMethod : function(){ var that = this; // Store a reference to this (myObject) in myMethod scope. var helperFunction = function() { // Child function. // Logs 'I can see the light' via scope chain because that = this. console.log(that.myProperty); // Logs 'I can see the light'. console.log(this); // Logs window object, if we don't use "that". }(); } } myObject.myMethod(); // Invoke myMethod. </script></body></html>
call()
或 apply()
控制 this
的值
this
的值通常由调用函数的上下文确定(除非使用 new 关键字,稍后会详细介绍),但您可以使用 this
的值>apply() 或 call()
来定义调用函数时 this
指向什么对象。使用这些方法就像在说:“嘿,调用 X 函数,但告诉该函数使用 Z 对象作为 this
的值。”通过这样做,JavaScript 确定 this
值的默认方式将被覆盖。
在下一个示例中,我们创建一个对象和一个函数。然后我们通过 call()
调用该函数,以便函数内 this
的值使用 myObject
作为其上下文。 myFunction
函数内的语句将使用属性填充 myObject
,而不是填充头对象。我们更改了 this
(在 myFunction
内部)引用的对象。
示例:sample105.html
<!DOCTYPE html><html lang="en"><body><script> var myObject = {}; var myFunction = function (param1, param2) { // Set via call(), 'this' points to myObject when function is invoked. this.foo = param1; this.bar = param2; console.log(this) // Logs Object {foo = 'foo', bar = 'bar'} }; myFunction.call(myObject, 'foo', 'bar'); // Invoke function, set this value to myObject. console.log(myObject) // Logs Object {foo = 'foo', bar = 'bar'} </script></body></html>
在前面的示例中,我们使用了 call()
,但也可以使用 apply()
。两者之间的区别在于函数参数的传递方式。使用 call()
,参数只是逗号分隔的值。使用 apply()
,参数值在数组内部传递,如以下示例所示。
示例:sample106.html
<!DOCTYPE html><html lang="en"><body><script> var myObject = {}; var myFunction = function (param1, param2) { // Set via apply(), this points to myObject when function is invoked. this.foo = param1; this.bar = param2; console.log(this) // Logs Object {foo = 'foo', bar = 'bar'} }; myFunction.apply(myObject, ['foo', 'bar']); // Invoke function, set this value. console.log(myObject) // Logs Object {foo = 'foo', bar = 'bar'} </script></body></html>
这里您需要学习的是,您可以覆盖 JavaScript 在函数作用域中确定 this
值的默认方式。
this
关键字当使用 new
关键字调用函数时,构造函数中声明的 this
的值指的是实例本身。换句话说:在构造函数中,我们可以在实际创建对象之前通过 this
来利用该对象。在这种情况下, this
的默认值的更改方式类似于使用 call()
或 apply()
。
在下面的示例中,我们设置了一个 Person
构造函数,该函数使用 this
来引用正在创建的对象。当创建 Person
的实例时,this.name
将引用新创建的对象,并在新对象中放置一个名为 name 的属性,并将参数 (name
) 中的值传递给构造函数。 p>
示例:sample107.html
<!DOCTYPE html><html lang="en"><body><script> var Person = function (name) { this.name = name || 'john doe'; // this will refer to the instance created. } var cody = new Person('Cody Lindley'); // Create an instance based on the Person constructor. console.log(cody.name); // Logs 'Cody Lindley'. </script></body></html>
同样,当使用 new
关键字调用构造函数时,this
指的是“将成为的对象”。如果我们没有使用 new
关键字,则 this
的值将是调用 Person
的上下文 - 在本例中为头对象。让我们看一下以下场景:
示例:sample108.html
<!DOCTYPE html><html lang="en"><body><script> var Person = function (name) { this.name = name || 'john doe'; } var cody = Person('Cody Lindley'); // Notice we did not use 'new'. console.log(cody.name); // Undefined. The value is actually set at window.name console.log(window.name); // Logs 'Cody Lindley'. </script></body></html>
this
引用构造函数实例当在添加到构造函数 prototype
属性的函数中使用时,this
指的是调用该方法的实例。假设我们有一个自定义 Person()
构造函数。作为参数,它需要人的全名。如果我们需要访问人员的全名,我们将 whatIsMyFullName
方法添加到 Person.prototype
中,以便所有 Person
实例继承该方法。当使用 this
时,该方法可以引用调用它的实例(以及它的属性)。
这里我演示了创建两个Person
对象(cody
和lisa
)以及继承的whatIsMyFullName
方法,其中包含this关键字来访问实例。
示例:sample109.html
<!DOCTYPE html><html lang="en"><body><script> var Person = function (x) { if (x) { this.fullName = x }; }; Person.prototype.whatIsMyFullName = function () { return this.fullName; // 'this' refers to the instance created from Person() } var cody = new Person('cody lindley'); var lisa = new Person('lisa lindley'); // Call the inherited whatIsMyFullName method, which uses this to refer to the instance. console.log(cody.whatIsMyFullName(), lisa.whatIsMyFullName()); /* The prototype chain is still in effect, so if the instance does not have a fullName property, it will look for it in the prototype chain. Next, we add a fullName property to both the Person prototype and the Object prototype. See the notes that follow this sample. */ Object.prototype.fullName = 'John Doe'; var john = new Person(); // No argument is passed so fullName is not added to the instance. console.log(john.whatIsMyFullName()); // Logs 'John Doe'. </script></body></html>
这里要带走的概念是 that
关键字 this 用于在 prototype
对象中包含的方法内部使用时引用实例。如果实例不包含该属性,则开始查找原型。
如果 this
指向的实例或对象不包含所引用的属性,则应用适用于任何属性查找的相同规则,并且将在原型链上“查找”该属性。因此,在我们的示例中,如果 fullName
属性未包含在我们的实例中,则将在 Person.prototype.fullName
中查找 fullName
属性,然后在 Object.prototype.fullName
中查找。
위 내용은 'this' 키워드 이해하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!