apply、call、bind 实现和this指向问题

2019-12-16  本文已影响0人  行走的蛋白质

var fullName = 'language'
var obj = {
    fullName: 'javascript',
    prop: {
        getFullName: function() {
            return this.fullName
        }
    }
}
console.log(obj.prop.getFullName()) // undefined 方法调用前面有点则点前面就是 this => obj.prop => obj.prop.fullName => undefined
var test = obj.prop.getFullName
console.log(test()) // language
var name = 'window'
var Tom = {
    name: 'Tom',
    show: function() {
        console.log(this.name)
    },
    wait: function() {
        var fun = this.show
        fun() // 直接执行,管你在哪呢,this 就是 window
    }
}
Tom.wait() // window
this
// 1. 最普通的函数调用
function fun1() {
    console.log(this) // Window
}
fun1()

// 2. 函数嵌套
function fun1() {
    function fun2() {
        console.log(this) // Window
    }
    fun2()
}
fun1()

// 3. 把函数赋值之后在调用
var a = 1
var obj1 = {
    a: 2,
    fun1: function() {
        console.log(this.a)
    }
}
var fun2 = obj1.fun1
fun2() // 1
// 如果想输出 2 则需要显式的绑定 obj1 如下
fun2.call(obj1) // 2

// 4. 回调函数
var num1 = 1
function fun1(fun) {
    fun()
    console.log(this.num1)
}
fun1(fun2) // 1
function fun2() {
    var num1 = 2
}
// 改写如下:成自执行函数
var num1 = 1
function fun1() {
    (function fun2() {
        var num1 = 2
    })()
    console.log(this.num1)
}
fun1() // 1
// 上述可推理出 setTimeout 这个自执行函数就约等于回调函数,所以他的 this 也是 window 代码如下:
setTimeout(function fun1() {
    console.log(this) // window
    function fun2() {
        console.log(this) // window
    }
    fun2()
}, 0)
// 1. 直接调用
var a = 1
var obj1 = {
    a: 2,
    fun1: function() {
        console.log(this.a) // 2
    }
}
obj1.fun1()

// 2. DOM 对象绑定事件调用
// 页面监听 click 事件属于方法调用,this 指向 DOM 源对象
document.addEventListener('click', function(e) {
    console.log(this) // document
    setTimeout(function() {
        console.log(this) // Window
    }, 200)
}, false)

构造器调用模式示例如下:

function Person(name, age) {
    this.name = name
    this.age = age
    this.sayName = function () {
        console.log(this.name)
    }
}   
var person1 = new Person('xiaoming', 22)
person1.sayName() // 'xiaoming'
function test2() {
    return () => {
        return () => {
            console.log(this) 
        }
    }
}
console.log(test2()()()) // Window

多次 bind 实例探究:

let test3 = { }
let fun3 = function () {
    console.log(this)
}
fun3.bind().bind(test3)() // => ?

如上示例 愚钝的笔者是看不出来输出结果的所以我只能用变形的方法来更清楚的看一下执行函数的顺序如下:

let test3 = { }
let fun3 = function () {
    console.log(this)
}
let fun4 = function fun5() {
    return function () {
        return fun3.apply()
    }.apply(test3)
}
fun4()

这样改变就比较清晰的看到不管给函数 bind 几次,fun3 中的 this 永远由第一次 bind 来决定,即为 window。

let test6 = { name: 'test6' }
function fun6() {
    console.log(this.name)
}
fun6.bind(test6)() // test6

如果发生多个规则同时出现,则需要遵循优先级:new 方式优先级最高,bind call apply 其次,接下来是 test1.fun() 调用,最后是直接调用,同时箭头函数的 this 一旦被绑定就不可改变。

this指向流程图.png
call、apply
obj1.fun1() => obj1.fun1.call(obj1)
fun1() => fun1.call(null)
fun1(fun2) => fun1.call(null, fun2)
Function.prototype.call = function(obj) {
    if(typeof this != 'function') {
        throw Error('this is not a function')
    }
    // 判断第一个参数如果没有则指向 window
    obj = obj || window
    // 取出外层参数 call
    const args1 = Array.prototype.slice.call(arguments, 1)
    // apply const args1 = arguments[1]
    // 将 this 放入到绑定的对象里面
    const fn = Symbol('fn')
    obj[fn] = this
    // 执行保存的函数, 这个时候作用域就是在绑定对象的作用域下执行,改变的this的指向
    const result = obj[fn](...args1)
    // 删除上述绑定的方法
    delete obj[fn]
    return result
}
bind
// bind 返回值是函数
var object1 = {
    name: 'bind'
}
function fun1() {
    console.log(this.name)
}
var bind = fun1.bind(object1)
console.log(bind) // ƒ fun1() { console.log(this.name) }
bind() // bind

// 参数的使用
function fun1 (a, b, c) {
    console.log(a, b, c)
}
var fun2 = fun1.bind(null, 'bind')

fun1('1', '2', '3') // 1, 2, 3
fun2('1', '2', '3') // bind, 1, 2 
fun2('2', '3') //bind, 2, 3
fun1.call(null, 'bind') // bind, undefined, undefined
Function.prototype.bind = function(obj) {
    if(typeof this != 'function') {
        throw Error('this is not a function')
    } 
    // 判断第一个参数如果没有则指向 window
    obj = obj || window
    // 缓存 this 出来,防止被改变
    const self = this
    // 取出外层参数
    const args1 = Array.prototype.slice.call(arguments, 1)
    // 返回一个函数 
    const result = function() {
        // 绑定 this 到 obj 上并执行方法,参数进行内外合并
        // return self.apply(obj, args1.concat([...arguments]))
        // 如果函数放在 new 后面进行调用,则需要判断当前 this 是不是属于绑定函数的实例
        return self.apply(this instanceof result ? this : obj, args1.concat([...arguments]))
    }
    // 维护好原型链
    const ret = function() {}
    if(this.prototype) {
        ret.prototype = this.prototype
    }
    // 下行的代码使 result.prototype是 ret 的实例,因此返回的 reslt 若作为 new 的构造函数
    // new 生成的新对象作为 this 传入 result, 新对象的 __proto__ 就是 ret 的实例
    result.prototype = new ret()
    return result
}
应用场景
var arr = [1, 2, 3, 4, 5]
var max = Math.max.apply(null, arr)
var min = Math.min.apply(null, arr)
console.log(max, ' --- ', min) // 5 " --- " 1
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var total = [].push.apply(arr1, arr2);//6
// arr1 [1, 2, 3, 4, 5, 6]
// arr2 [4,5,6]
function isArray(obj){
    return Object.prototype.toString.call(obj) == '[object Array]';
}
isArray([]) // true
isArray('dot') // false
function Person(name,age){
    // 这里的this都指向实例
    this.name = name
    this.age = age
    this.sayAge = function(){
        console.log(this.age)
    }
}
function Female(){
    Person.apply(this,arguments)//将父元素所有方法在这里执行一遍就继承了
}
var dot = new Female('Dot',2)
call、apply和bind函数存在的区别: 简单实现请戳这里。。。

bind返回对应函数, 便于稍后调用; apply, call则是立即调用。
除此外, 在 ES6 的箭头函数下, call 和 apply 将失效, 对于箭头函数来说:

上一篇 下一篇

猜你喜欢

热点阅读