js 改變this指向的幾種方法(個人學習筆記)

2022-04-02 00:23:56 字數 1354 閱讀 7909

兩中方法都能改變this指向,很類似,區別主要是第二個以後引數,

用法:a.call(b,1,2);   表示要把a函式的this指向修改為b的this指向,並且執行a函式,傳進去的引數是(1,2)

//

function

say(arg1,arg2);

var obj =

}say.call(obj,'one','two');//

tom one two

say.spply(obj,['one','two']);//

tom one two 效果一樣

2.bind()

作用:bind()方法會建立乙個新函式,稱為繫結函式,當呼叫這個繫結函式時,繫結函式會以建立它時傳入 bind()方法的第乙個引數作為 this,傳入 bind() 方法的第二個以及以後的引數加上繫結函式執行時本身的引數按照順序作為原函式的引數來呼叫原函式。

用法:

var foo =.bind(this

));//這裡的this是eventbind的this,即指向的是foo

}}

注意:多次bind無效,按第一次算

總結一下

3.new   

new執行原理是:

new animal('cat') = ;//

先定義乙個空物件

obj.__proto__ = animal.prototype;//

把 obj 的__proto__ 指向建構函式 animal 的原型物件 prototype,此時便建立了 obj 物件的原型鏈:obj->animal.prototype->object.prototype->null

var result = animal.call(obj,"cat");//

改變this指向,從animal改變到obj上

return

typeof result === 'object'? result : obj; //

返回}

用法:

function

fn()

var a = new fn();//

this指向a

console.log(a.user); //

追夢子

4.return

在建構函式的時候,使用return進行返回乙個object的時候,當去new乙個例項物件的時候,會將this指向改變為return的object;

用法:

function

fn()

; }

var a = new

fn;

console.log(a.user);

//111

js改變this指向的方法

語法 函式.call this,arg1,arg2,arg3,arg4 第乙個引數用來指定函式內部的this指向,後面的引數是函式執行時所需的實參。window.color red document.color yellow var s1 function changecolor changecol...

改變JS中的this指向的方法

1.全域性呼叫 函式名 指向 window 2.物件呼叫 物件.函式名 誰呼叫指向誰 前面是誰就指向誰 3.自執行的函式 指向window 4.事件處理函式 指向事件源 5.定時器處理函式 指向事件源 6.函式定義了未呼叫的時候指向不確定 call 語法 函式名.call 你要改變的函式的 this...

改變this指向的三種方法

function box a,b 方法一 bind 不會自動呼叫函式 let obj box box.bind obj,1,2 box this 方法二 call 函式 第乙個引數 是乙個物件 用這個改變函式內部的this,並且呼叫這個函式 其他的引數 都會作為box函式的引數 box.call 1...