咱們知道在 javascript 中 call 和 apply 以及 bind 均可以改變 this 指向,那麼它們是怎麼實現的呢?彼此之間有什麼區別呢?首先咱們先來分別解析一下它們,這篇文章簡單的介紹了實現 call() , apply() , bind()的思路javascript
var leo = { name: "Leo", sayHai: function () { return "Hi I'm " + this.name }, add: function (a, b) { console.log(this) return a + b }, } var neil = { name: "Neil", } console.log(leo.sayHai.call(neil)) //Neil console.log(leo.sayHai.call(null)) //undefine
如上面輸出結果能夠看出:
1.call 方法的第一個參數用於改變 this 指向,可是若是傳入 null/undefined 值,this 會指向 window
2.call 方法須要把實參按照形參的個數傳進去
如今咱們已經知道如何使用 call 以及它的規則,那麼咱們來封裝一個本身的 call 方法java
//ES3實現方法利用了eval()函數,將字符串當作JavaScript表達是執行 Function.prototype.es3call = function (ctx) { var ctx = ctx || global || window ctx.fn = this var args = [] for (var i = 1; i < arguments.length; i++) { args.push("arguments[" + i + "]") } var result = eval("ctx.fn(" + args.join(",") + ")") delete ctx.fn return result } //ES6實現方法利用了擴展運算符rest運算符 Function.prototype.es6call = function (ctx) { var ctx = ctx || window || global ctx.fn = this var args = [] for (var i = 1; i < arguments.length; i++) { args.push("arguments[" + i + "]") } const result = ctx.fn(...args) return result } console.log(leo.sayHai.es3call(neil)) //Neil console.log(leo.sayHai.es3call(null)) //undefine console.log(leo.sayHai.es6call(neil)) //Neil console.log(leo.sayHai.es6call(null)) //undefine
console.log(leo.add.apply(neil, [2, 3])) //neil 5 console.log(leo.add.apply(null, [2, 3])) //window or global 5
1.apply 方法的第一個參數用於改變 this 指向,可是若是傳入 null/undefined 值,this 會指向 window
2.apply 方法的第二個參數須要傳入一個實參列表,也就是 argumentses6
//ES3實現方法利用了eval()函數,將字符串當作JavaScript表達是執行 Function.prototype.es3apply = function (ctx, arr) { var ctx = ctx || global || window ctx.fn = this var result = null if (!arr) { result = ctx.fn() } else { if (!(arr instanceof Array)) throw new Error("params must Array") var args = [] for (var i = 0; i < arr.length; i++) { args.push("arr[" + i + "]") } result = eval("ctx.fn(" + args.join(",") + ")") } delete ctx.fn return result } //ES6實現方法利用了擴展運算符rest運算符 Function.prototype.es6apply = function (ctx, arr) { var ctx = ctx || global || window ctx.fn = this var result = null if (!arr) { result = ctx.fn() } else { if (!(arr instanceof Array)) throw new Error("params must Array") var args = [] for (var i = 0; i < arr.length; i++) { args.push("arr[" + i + "]") } result = ctx.fn(...args) } delete ctx.fn return result }
console.log(leo.add.es3apply(neil, [2, 3])) //neil 5 console.log(leo.add.es3apply(null, [2, 3])) //window or global 5 console.log(leo.add.es6apply(neil, [2, 3])) //neil 5 console.log(leo.add.es6apply(null, [2, 3])) //window or global 5
var value = "window" var obj = { value: "obj", } Parent.prototype.value = "parent" function Parent() {} Child.prototype = new Parent() function Child() {} function show(name) { console.log(this.value, name) } show() //window undefined var newShow1 = show.bind(obj) newShow1() //obj undefined var newShow2 = show.bind(null) newShow2() //window undefined var newShow3 = show.bind(obj, "test") //函數擁有預設的初始參數 newShow3() //obj test new newShow3() //undefined test var oS = Child.bind(obj) var fn = new oS() console.log(fn, fn.value) //Child{} "parent" 當使用new 操做符調用綁定函數時,參數obj無效。
根據上面的運行結果,咱們能夠總結一下 bind 的用法規則:
1.bind() 函數會建立一個新函數(稱爲綁定函數),新函數與被調函數(綁定函數的目標函數)具備相同的函數體
2.bind 方法的第一個參數也是用於改變 this 指向,若是傳入 null/undefined,this 會指向 window 3.一個綁定函數也能使用 new 操做符建立對象:這種行爲就像把原函數當成構造器。提供的 this 值被忽略
4.bind 方法能夠使函數擁有預設的初始參數。這些參數(若是有的話)做爲 bind()的第二個參數跟在 this(或其餘對象)後面,以後它們會被插入到目標函數的參數列表的開始位置,傳遞給綁定函數的參數會跟在它們的後面。app
//ES3實現方法 Function.prototype.es3bind = function (ctx) { var ctx = ctx || global || window var self = this var args = Array.prototype.slice.call(arguments, 1) if (typeof this !== "function") throw new Error("what is trying to be bind is not callback") var temp = function () {} var fn = function () { var fnArgs = Array.prototype.slice.call(arguments, 0) return self.apply(this instanceof fn ? this : ctx, args.concat(fnArgs)) } // 先讓 temp 的原型方法指向 _this 即原函數的原型方法,繼承 _this 的屬性 temp.prototype = this.prototype // 再將 fn 即要返回的新函數的原型方法指向 temp 的實例化對象 // 這樣,既能讓 fn 繼承 _this 的屬性,在修改其原型鏈時,又不會影響到 _this 的原型鏈 fn.prototype = new temp() //原型繼承 return fn } //ES6實現方法 Function.prototype.es6bind = function (ctx, ...rest) { if (typeof this !== "function") throw new Error("what is trying to be bind is not callback") var self = this return function F(...args) { if (this instanceof F) { return new self(...rest, ...args) } return self.apply(ctx, rest.concat(args)) } }
show() //window undefined var newShow1 = show.es3bind(obj) newShow1() //obj undefined var newShow2 = show.es3bind(null) newShow2() //window undefined var newShow3 = show.es3bind(obj, "test") //函數擁有預設的初始參數 newShow3() //obj test new newShow3() //undefined test var oS = Child.es3bind(obj) var fn = new oS() console.log(fn, fn.value) //Child{} "parent" 當使用new 操做符調用綁定函數時,參數obj無效。 show() //window undefined var newShow1 = show.es6bind(obj) newShow1() //obj undefined var newShow2 = show.es6bind(null) newShow2() //window undefined var newShow3 = show.es6bind(obj, "test") //函數擁有預設的初始參數 newShow3() //obj test new newShow3() //undefined test var oS = Child.es6bind(obj) var fn = new oS() console.log(fn, fn.value) //Child{} "parent" 當使用new 操做符調用綁定函數時,參數obj無效。