const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
В JavaScript ключевое слово this относится к объекту.
Какой объект зависит от того, как этот вызывается (используется или вызывается).
Ключевое слово this относится к разным объектам в зависимости от того, как оно используется:
В объектном методе this относится к объекту.
Само по себе это относится к глобальному объекту.
В функции this относится к глобальному объекту.
В функции в строгом режиме это имеет значение не определено.
В событии this относится к элементу, получившему событие.
Такие методы, как call(), apply() и bind() может ссылаться на this на любой объект.
это не является переменной. Это ключевое слово. Вы не можете изменить значение this.
При использовании в методе объекта this ссылается на объект.
В примере вверху этой страницы this относится к объекту person.
Потому что метод fullName является методом объекта person.
fullName : function() {
return this.firstName + " " + this.lastName;
}Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
При использовании отдельно this относится к глобальному объекту.
Потому что это выполняется в глобальной области.
В окне браузера глобальным объектом является [object Window]:
let x = this; Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the window object:</p>
<p id="demo"></p>
<script>
let x = this;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
В строгом режиме при использовании отдельно this также ссылается на глобальный объект:
"use strict";
let x = this; Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the window object:</p>
<p id="demo"></p>
<script>
"use strict";
let x = this;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
В функции глобальный объект является привязкой по умолчанию для this.
В окне браузера глобальным объектом является [object Window]:
function myFunction() {
return this;
}Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the the window object:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = myFunction();
function myFunction() {
return this;
}
</script>
</body>
</html>
строгий режим JavaScript не допускает привязки по умолчанию.
Таким образом, при использовании в функции в строгом режиме это имеет значение не определено.
"use strict";
function myFunction() {
return this;
}Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In a function, by default, <b>this</b> refers to the global object.</p>
<p>Strict mode does not allow default binding, so <b>this</b> is:</p>
<p id="demo"></p>
<script>
"use strict";
document.getElementById("demo").innerHTML = myFunction();
function myFunction() {
return this;
}
</script>
</body>
</html>
В обработчиках событий HTML this относится к элементу HTML, получившему событие:
<button onclick="this.style.display='none'">
Click to
Remove Me!
</button>Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<button onclick="this.style.display='none'">Click to Remove Me!</button>
</body>
</html>
В этих примерах this является объектом person:
const person = {
firstName : "John",
lastName : "Doe",
id : 5566,
myFunction : function() {
return this;
}
};Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person object</b>.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName : "John",
lastName : "Doe",
id : 5566,
myFunction : function() {
return this;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.myFunction();
</script>
</body>
</html>
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " +
this.lastName;
}
};Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
т. е. this.firstName является свойством firstName объекта this (объекта person).
Методы call() и apply() являются предопределенными методами JavaScript.
Оба они могут использоваться для вызова метода объекта с другим объектом в качестве аргумента.
Метод вызова функции()
Метод Apply() функции
Метод функции связывания()
В приведенном ниже примере вызывается person1.fullName с аргументом person2, this относится к person2, даже если fullName является методом person1:
const person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person2 = {
firstName:"John",
lastName: "Doe",
}
// Return "John Doe":
person1.fullName.call(person2);Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example <strong>this</strong> refers to person2, even if it is a method of person1:</p>
<p id="demo"></p>
<script>
const person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person2 = {
firstName:"John",
lastName: "Doe",
}
let x = person1.fullName.call(person2);
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
С помощью метода bind() объект может заимствовать метод у другого объекта.
В этом примере создаются 2 объекта (человек и участник).
Объект-член заимствует метод полного имени из объекта person:
const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);Попробуйте сами →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Function bind()</h1>
<p>This example creates 2 objects (person and member).</p>
<p>The member object borrows the fullname method from person:</p>
<p id="demo"></p>
<script>
const person = {
firstName:"John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);
document.getElementById("demo").innerHTML = fullName();
</script>
</body>
</html>
Чтобы определить, к какому объекту относится this; используйте следующий приоритет порядка.
Объект
связывать()
применить() и вызвать()
Метод объекта
Глобальная область действия
Находится ли это в функции, вызываемой с помощью метода связывания()?
Находится ли это в функции, вызываемой с помощью apply()?
Находится ли это в функции, вызываемой с помощью call()?
Является ли это объектной функцией (методом)? <p>Находится ли это в функции в глобальной области видимости.