- Vue.js 2 Design Patterns and Best Practices
- Paul Halliday
- 306字
- 2021-06-24 18:33:07
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.
- Learning Karaf Cellar
- 智慧城市中的移動互聯(lián)網(wǎng)技術(shù)
- 計(jì)算機(jī)網(wǎng)絡(luò)工程實(shí)用教程(第2版)
- The Kubernetes Workshop
- 搶占下一個智能風(fēng)口:移動物聯(lián)網(wǎng)
- Scala Design Patterns.
- 云計(jì)算技術(shù)與標(biāo)準(zhǔn)化
- LwIP應(yīng)用開發(fā)實(shí)戰(zhàn)指南:基于STM32
- 5G非正交多址接入技術(shù):理論、算法與實(shí)現(xiàn)
- 物聯(lián)網(wǎng)基礎(chǔ)及應(yīng)用
- RestKit for iOS
- 通信系統(tǒng)實(shí)戰(zhàn)筆記:無處不在的信號處理
- 互聯(lián)網(wǎng)安全的40個智慧洞見(2018)
- 巧學(xué)活用CISCO網(wǎng)絡(luò)典型配置
- 5G智聯(lián)萬物:輕松讀懂5G應(yīng)用與智能未來