当前位置:网站首页>The interviewer asked: this point of JS
The interviewer asked: this point of JS
2022-06-28 01:47:00 【InfoQ】
Preface
JSnew、call、apply、this、 Inherit Interviewer asks series thisJSthisthisthisGlobal context
windowthis === window // true
'use strict'
this === window;
this.name = ' If Chuan ';
console.log(this.name); // If Chuan
Function context
Normal function call mode
// Nonstrict mode
var name = 'window';
var doSth = function(){
console.log(this.name);
}
doSth(); // 'window'
window.doSth()windowwindow.doSthdoSthnamewindow.nameES5window// Nonstrict mode
let name2 = 'window2';
let doSth2 = function(){
console.log(this === window);
console.log(this.name2);
}
doSth2() // true, undefined
letwindow.name2 and window.doSthundefinedthisundefined// Strict mode
'use strict'
var name = 'window';
var doSth = function(){
console.log(typeof this === 'undefined');
console.log(this.name);
}
doSth(); // true,// Report errors , because this yes undefined
JavaScriptcallapplydoSth.call(undefined);
doSth.apply(undefined);
callapplythisundefinednullwindowvar name = ' If Chuan ';
setTimeout(function(){
console.log(this.name);
}, 0);
// grammar
setTimeout(fn | code, 0, arg1, arg2, ...)
// It can also be a string of code . You can also pass other functions
// analogy setTimeout Function internal call fn Or execute the code `code`.
fn.call(undefined, arg1, arg2, ...);
Function in object ( Method ) Call mode
var name = 'window';
var doSth = function(){
console.log(this.name);
}
var student = {
name: ' If Chuan ',
doSth: doSth,
other: {
name: 'other',
doSth: doSth,
}
}
student.doSth(); // ' If Chuan '
student.other.doSth(); // 'other'
// use call The analogy is :
student.doSth.call(student);
// use call The analogy is :
student.other.doSth.call(student.other);
var studentDoSth = student.doSth;
studentDoSth(); // 'window'
// use call The analogy is :
studentDoSth.call(undefined);
call、apply、bind
Call mode
callapplyMDNcallapplyfun.call(thisArg, arg1, arg2, ...)
funthisthisthisnullundefinedthiswindowthisundefinedapplycallthisArgcallthisthisArgJSthisArgvar doSth = function(name){
console.log(this);
console.log(name);
}
doSth.call(2, ' If Chuan '); // Number{2}, ' If Chuan '
var doSth2 = function(name){
'use strict';
console.log(this);
console.log(name);
}
doSth2.call(2, ' If Chuan '); // 2, ' If Chuan '
thisArgJScallapplythiscallapplybindcallapplythisnewbind()thisnewbindsetTimeoutthisArgobjectthisthisArgthisJSbindcallapplythisArgbindConstructor call mode
function Student(name){
this.name = name;
console.log(this); // {name: ' If Chuan '}
// Equivalent to returning
// return this;
}
var result = new Student(' If Chuan ');
new- A new object is created .
- This object will be executed
[[Prototype]]( That is to say__proto__) link .
- The generated new object is bound to the function call
this.
- adopt
newEach object created will eventually be[[Prototype]]Linked to this functionprototypeOn the object .
- If the function does not return an object type
Object( containFunctoin,Array,Date,RegExg,Error), thatnewThe function call in the expression automatically returns the new object .
newthisnewfunction Student(name){
this.name = name;
// return function f(){};
// return {};
}
var result = new Student(' If Chuan ');
console.log(result); {name: ' If Chuan '}
// If the return function f, be result Is the function f, If it's an object {}, be result It's the object {}
typeofJSnewThe call pattern in the prototype chain
function Student(name){
this.name = name;
}
var s1 = new Student(' If Chuan ');
Student.prototype.doSth = function(){
console.log(this.name);
}
s1.doSth(); // ' If Chuan '
ES6classclass Student{
constructor(name){
this.name = name;
}
doSth(){
console.log(this.name);
}
}
let s1 = new Student(' If Chuan ');
s1.doSth();
babeles6es5babeljs Website conversion test 'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Student = function () {
function Student(name) {
_classCallCheck(this, Student);
this.name = name;
}
_createClass(Student, [{
key: 'doSth',
value: function doSth() {
console.log(this.name);
}
}]);
return Student;
}();
var s1 = new Student(' If Chuan ');
s1.doSth();
ES6classArrow function call mode
thissuperargumentsnew.targetnewthisthisthisthisthisvar name = 'window';
var student = {
name: ' If Chuan ',
doSth: function(){
// var self = this;
var arrowDoSth = () => {
// console.log(self.name);
console.log(this.name);
}
arrowDoSth();
},
arrowDoSth2: () => {
console.log(this.name);
}
}
student.doSth(); // ' If Chuan '
student.arrowDoSth2(); // 'window'
thisthiswindowcallapplybindthisthiscallapplybindthisvar student = {
name: ' If Chuan ',
doSth: function(){
console.log(this.name);
return () => {
console.log('arrowFn:', this.name);
}
}
}
var person = {
name: 'person',
}
student.doSth().call(person); // ' If Chuan ' 'arrowFn:' ' If Chuan '
student.doSth.call(person)(); // 'person' 'arrowFn:' 'person'
DOM
Event handler function call
addEventerListener、attachEvent、onclick
<button class="button">onclick</button>
<ul class="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
var button = document.querySelector('button');
button.onclick = function(ev){
console.log(this);
console.log(this === ev.currentTarget); // true
}
var list = document.querySelector('.list');
list.addEventListener('click', function(ev){
console.log(this === list); // true
console.log(this === ev.currentTarget); // true
console.log(this);
console.log(ev.target);
}, false);
</script>
onclickaddEventerListenerIE6~IE8attachEventthiswindowev.currentTargetev.targetev.currentTargetev.targetulliulev.currentTargetev.targetInline event handler function call
<button class="btn1" onclick="console.log(this === document.querySelector('.btn1'))"> Point me </button>
<button onclick="console.log((function(){return this})());"> Order me again </button>
buttontruewindowthisobjectgettersetterthisnew Function()evalnewcall、apply、bindpriority
thisthiswindowvar name = 'window';
var person = {
name: 'person',
}
var doSth = function(){
console.log(this.name);
return function(){
console.log('return:', this.name);
}
}
var Student = {
name: ' If Chuan ',
doSth: doSth,
}
// Ordinary function call
doSth(); // window
// Function calls on objects
Student.doSth(); // ' If Chuan '
// call、apply call
Student.doSth.call(person); // 'person'
new Student.doSth.call(person);
Student.doSth.call(person)newnewnew (Student.doSth.call)(person)Function.prototype.callapplybindnewUncaught TypeError: Student.doSth.call is not a constructor
[[Call]][[Constructor]][[Call]][[Constructor]]callapplybind[[Constructor]]call(apply、bind)newbindnewmdnbindployfillnewbindmdnJSbindnewnewcall、apply、bindsummary
thisthisnewcall : Bind to the newly created object , Be careful : ShowreturnFunction or object , The return value is not a newly created object , It's an explicit return function or object .<br>
callperhapsapply( perhapsbind) call : In strict mode , Bind to the first parameter specified . Non strict mode ,nullandundefined, Point to global object ( Browser iswindow), The rest of the values point tonew Object()Wrapped object .<br>
- Function calls on objects : Bind to that object .<br>
- Ordinary function call : To bind in strict mode
undefined, Otherwise, bind to the global object .<br>
ES6thiswindowES6self = thisDOMDOMIE6~IE8attachEventthis ø = Object.create(null)thisnew、call、apply、bindExamination questions
thisExtended reading
边栏推荐
- Data analysts too hot? Monthly income 3W? Tell you the true situation of this industry with data
- 【牛客討論區】第四章:Redis
- Ten thousand words long article understanding business intelligence (BI) | recommended collection
- 基于AM335X开发板 ARM Cortex-A8——Acontis EtherCAT主站开发案例
- Huawei partners and Developers Conference 2022 | Kirin software cooperates with Huawei to jointly build the computing industry and create a digital intelligence future
- Solve storage problems? WMS warehouse management system solution
- Is it safe to open an account for mobile stocks? Where can I open an account for buying stocks?
- Arrays. Aslist() pit
- [embedded foundation] memory (cache, ram, ROM, flash)
- 评价——灰色关联分析
猜你喜欢

9. Openfeign service interface call

美团动态线程池实践思路已开源

机器学习笔记 - 时间序列作为特征

Solon 1.8.3 发布,云原生微服务开发框架

什麼是數字化?什麼是數字化轉型?為什麼企業選擇數字化轉型?

Official announcement! Apache Doris graduated from the Apache incubator and officially became the top project of Apache!

SPuG - lightweight automatic operation and maintenance platform

如何理解 Transformer 中的 Query、Key 与 Value

Réseau neuronal pour la solution détaillée Multi - diagrammes de fondation zéro
![[embedded foundation] serial port communication](/img/b7/18fec20e2d5fa5f226c6f8bb1e93d2.png)
[embedded foundation] serial port communication
随机推荐
TI AM3352/54/59 工业核心板硬件说明书
Centos8 operation record command version Yum redis MySQL Nacos JDK
Maimai hot post: Why are big factories keen on making wheels?
【开源】开源系统整理-考试问卷等
ionic4实现半星评分
[embedded foundation] serial port communication
向excel中导入mysql中的数据表
Ten thousand words long article understanding business intelligence (BI) | recommended collection
What are the requirements for customizing the slip ring for UAV
PV操作原语
MySQL - function
I/o limit process and CPU limit process
万字长文看懂商业智能(BI)|推荐收藏
Set collection usage
如何高效读书学习
Evaluation - rank sum ratio comprehensive evaluation
Adobe Premiere基础-声音调整(音量矫正,降噪,电话音,音高换挡器,参数均衡器)(十八)
Import the data table in MySQL into Excel
什麼是數字化?什麼是數字化轉型?為什麼企業選擇數字化轉型?
Adobe Premiere基础-常用的视频特效(边角定位,马赛克,模糊,锐化,手写工具,效果控件层级顺序)(十六)