>  기사  >  웹 프론트엔드  >  "this" 키워드 이해하기

"this" 키워드 이해하기

PHPz
PHPz원래의
2023-08-30 17:05:09913검색

this 키워드 이해하기

함수를 생성하면 해당 함수에 사용할 수 있는 this 的关键字(在幕后),该关键字链接到函数运行的对象。换句话说,this라는 범위가 생성되지만 이는 함수가 속성이나 메서드로 갖는 객체에 대한 참조입니다.

이전 기사의 cody 개체를 살펴보겠습니다.

예: Sample98.html

으아악

getGender 함수 내에서 getGender 函数内部,我们如何在 cody 对象本身上使用点表示法 (cody.gender) 访问 gender 属性。可以使用 this 重写来访问 cody 对象,因为 this 指向 cody 개체 자체의 점 표기법(cody.gender)을 사용하여 gender 속성에 액세스하는 방법을 확인하세요.

개체는

개체를 가리키므로

재정의를 사용하여

개체에 액세스할 수 있습니다. this.gender 中使用的 this

예: Sample99.html

으아악 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.sayFoosayFoo 都指向相同的函数。但是,根据调用 sayFoo() 的位置(上下文),this

의 속성으로 인해 사용되었습니다.

window예: Sample100.html

으아악

분명히

의 값은 함수가 호출되는 상황에 따라 달라집니다. myObject.sayFoosayFoo가 모두 동일한 함수를 가리킨다는 점을 고려하세요. 하지만 (컨텍스트) sayFoo()가 호출되는 위치에 따라

의 값이 달라집니다.

도움이 된다면 헤더 개체를 명시적으로 사용하는 동일한 코드를 참조하세요(thisarguments).


예: Sample101.html

으아악 this함수를 전달하거나 함수에 대해 여러 참조를 만들 때 함수를 호출하는 상황에 따라 this의 값이 변경된다는 점을 명심하세요.

this 在一个包含在另一个函数中的函数内部使用时会发生什么。坏消息是在 ECMA 3 中,this 迷失了方向并引用了头对象(浏览器中的 window인수를 제외한 모든 변수는 어휘 범위를 존중합니다

func2func3 中的 this 迷失了方向,并且不是指向 myObject

키워드는 중첩된 함수의 헤더 개체를 참조합니다

다른 함수 내에 포함된 함수 내에서

를 사용하면 어떻게 되는지 궁금하실 것입니다. 나쁜 소식은 ECMA 3에서

가 길을 잃고 함수가 정의된 객체 대신 헤더 객체(브라우저의

객체)를 참조했다는 것입니다. foo.func1 时会发生什么。当在 foo.func1 (函数中的函数)内部调用匿名函数时,匿名函数内部的 this

아래 코드에서는 func2func3

가 손실되어 myObject가 아닌 헤드 개체를 가리킵니다.

예: Sample102.htmlthis 으아악

좋은 소식은 이 문제가 ECMAScript 5에서 해결된다는 것입니다. 지금쯤이면 특히 함수를 다른 함수에 값으로 전달하기 시작할 때 이러한 딜레마를 인식해야 합니다.

다음 예와 익명 함수를 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对象(codylisa)以及继承的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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.