当前位置:网站首页>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
边栏推荐
- Is it safe to open a stock account online now? Select a listed securities firm, and the fastest time to open an account is 8 minutes
- How to build dual channel memory for Lenovo Savior r720
- 解决ionic4 使用hammerjs手势 press 事件,页面无法滚动问题
- Google Earth engine (GEE) -- an error caused by the imagecollection (error) traversing the image collection
- Zhang Fan: the attribution of flying pig after advertising based on causal inference technology
- Maimai hot post: Why are big factories keen on making wheels?
- Qu'est - ce que la numérisation? Qu'est - ce que la transformation numérique? Pourquoi les entreprises choisissent - elles la transformation numérique?
- Adobe Premiere Basics - common video effects (corner positioning, mosaic, blur, sharpen, handwriting tools, effect control hierarchy) (16)
- 嵌入式必学!硬件资源接口详解——基于ARM AM335X开发板 (下)
- Meituan dynamic thread pool practice idea has been open source
猜你喜欢

Adobe Premiere基础-常用的视频特效(裁剪,黑白,剪辑速度,镜像,镜头光晕)(十五)

Réseau neuronal pour la solution détaillée Multi - diagrammes de fondation zéro

Proe/creo product structure design - continuous research

零基礎多圖詳解圖神經網絡

How to understand query, key and value in transformer
![pytorch_lightning.utilities.exceptions.MisconfigurationException: You requested GPUs: [1] But...](/img/b4/8921c3ca5cd5a547768489d4a79202.png)
pytorch_lightning.utilities.exceptions.MisconfigurationException: You requested GPUs: [1] But...

TIA botu_ Concrete method of making analog input and output Global Library Based on SCL language

Adobe Premiere基础-编辑素材文件常规操作(脱机文件,替换素材,素材标签和编组,素材启用,便捷调节不透明度,项目打包)(十七)

Ten thousand words long article understanding business intelligence (BI) | recommended collection

The flutter slivereappbar is fully parsed. All the effects you want are here!
随机推荐
Is it safe to open an account online now? Novice is just on the road, ask for the answer
Transformer论文逐段精读
药物发现综述-01-药物发现概述
Adobe Premiere Basics - common video effects (cropping, black and white, clip speed, mirroring, lens halo) (XV)
Interface component telerik UI for WPF Getting Started Guide - how to switch custom styles using themes
Can you open an account for stock trading in flush? Is it safe?
Implementation of timed tasks in laravel framework
How to study efficiently
Réseau neuronal pour la solution détaillée Multi - diagrammes de fondation zéro
The flutter slivereappbar is fully parsed. All the effects you want are here!
Adobe Premiere基础-编辑素材文件常规操作(脱机文件,替换素材,素材标签和编组,素材启用,便捷调节不透明度,项目打包)(十七)
Zhang Fan: the attribution of flying pig after advertising based on causal inference technology
766. 托普利茨矩阵
怎样能低成本构建一个电商平台
Evaluation - grey correlation analysis
How to optimize the "message" list of IM
N methods of data De duplication using SQL
How about the market application strength of large-size conductive slip rings
Adobe Premiere基础-声音调整(音量矫正,降噪,电话音,音高换挡器,参数均衡器)(十八)
Is it safe to open an online futures account?