三者都是改變 this 指向的 api
用法
apply:xxx.apply(this, [arg1, arg2])
call:xxx.call(this, arg1, arg2)
bind:xxx.bind(this, arg1, arg2)
區別
主要是傳參方式和執行方式不同
-
apply、call 的區別:接受引數的方式不一樣
-
bind:不立即執行,而 apply、call 立即執行
栗子
初始狀態
let Person = function(name, age) {
this.name = name;
this.age = age;
};
let Student = function() {
this.class = 'classA';
this.run = function() {
console.log(this);
};
};
let student = new Student();
student.run();

可以看見這個時候列印的 this 是指向 Student 建構式,并且和 Person 建構式沒有任何關聯
使用 apply 改變 this 指向
let Person = function(name, age) {
this.name = name;
this.age = age;
};
let Student = function() {
this.class = 'classA';
this.run = function() {
Person.apply(this, ['xiaoming', 20]);
console.log(this);
};
};
let student = new Student();
student.run();

這個時候 this 已經指向了 Person 建構式了
使用 call 改變 this 指向
let Person = function(name, age) {
this.name = name;
this.age = age;
};
let Student = function() {
this.class = 'classA';
this.run = function() {
Person.call(this, 'xiaoming', 20);
console.log(this);
};
};
let student = new Student();
student.run();

這個時候 this 已經指向了 Person 建構式了
使用 bind 改變 this 指向
let ex = '';
let Person = function(name, age) {
this.name = name;
this.age = age;
};
let Student = function() {
this.class = 'classA';
this.run = function() {
ex = Person.bind(this, 'xiaoming', 20);
console.log(this);
};
};
let student = new Student();
student.run();
ex();

使用 bind 的話,需要執行了 this 改變才會生效
總結:使用 apply、call 和 bind 確實可以改變 this 指向,但是原有物件的屬性也跟著一起過去了
文章的內容/靈感都從下方內容中借鑒
-
【持續維護/更新 500+前端面試題/筆記】https://github.com/noxussj/Interview-Questions/issues
-
【大資料可視化圖表插件】https://www.npmjs.com/package/ns-echarts
-
【利用 THREE.JS 實作 3D 城市建模(珠海市)】https://3d.noxussj.top/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/297036.html
標籤:其他
