官术网_书友最值得收藏!

How 'this' works within JavaScript

Within JavaScript, this has varying contexts that range from the global window context to eval, newable, and function contexts. As the default context for this relates to the global scope, this is our window object:

/**
* Outputting the value of this to the console in the global context returns the Window object
*/
console.log(this);

/**
* When referencing global Window objects, we don't need to refer to them with this, but if we do, we get the same behavior
*/
alert('Alert one');
this.alert('Alert two');

The context of this changes depending on where we are in scope. This means, that if we had a Student object with particular values, such as firstName, lastName, grades, and so on, the context of this would be related to the object itself:

/**
* The context of this changes when we enter another lexical scope, take our Student object example:
*/
const Student = {
firstName: 'Paul',
lastName: 'Halliday',
grades: [50, 95, 70, 65, 35],
getFullName() {
return `${this.firstName} ${this.lastName}`
},
getGrades() {
return this.grades.reduce((accumulator, grade) => accumulator + grade);
},
toString() {
return `Student ${this.getFullName()} scored ${this.getGrades()}/500`;
}
}

When we run the preceding code with console.log(Student.toString()), we get this: Student Paul Halliday scored 315/500 as the context of this is now scoped to the object itself rather than the global window scope.

If we wanted to display this in the document we could do it like so:

let res = document.createTextNode(Student.toString());
let heading = document.createElement('h1');
heading.appendChild(res);
document.body.appendChild(heading);

Notice that, with the preceding code, once again we don't have to use this as it isn't needed with the global context.

Now that we have an understanding of how this works at a basic level, we can investigate how Vue proxies this inside of our instances to make interacting with the various properties much easier.

主站蜘蛛池模板: 乌兰察布市| 台江县| 汕尾市| 墨玉县| 广安市| 新密市| 保定市| 博白县| 保定市| 将乐县| 延边| 崇左市| 家居| 青铜峡市| 云阳县| 娱乐| 阳朔县| 定襄县| 舞钢市| 修文县| 富蕴县| 永清县| 沛县| 黄浦区| 安吉县| 邹平县| 上蔡县| 应城市| 高雄市| 葵青区| 太白县| 班玛县| 旺苍县| 淮阳县| 肃宁县| 中卫市| 聊城市| 江山市| 海林市| 安新县| 河源市|