美文网首页
Function call 和 bind 区别?

Function call 和 bind 区别?

作者: 莫帆海氵 | 来源:发表于2021-04-08 23:55 被阅读0次

Function.prototype.bind()

会创建一个新的函数,使用 bind 的第一个参数作为 this 来执行一个函数,其余参数传入执行的函数

function print() {
    console.log('print', this.x)
}

var tb = { x: 9 }
var fn = print.bind(tb)

fn() // print 9

Function.prototype.call()

使用一个指定的 this 值来执行一个函数,第一个参数作为 this,其余参数传入执行的函数

function print() {
    console.log('print', this.x)
}

var tb = { x: 99 }

print.call(null) // print undefined
print.call(tb) // print 99

总结

  • 都是可以改变执行函数的 this 指向
  • bind 会返回一个新函数,call 直接执行函数
  • bind 和 call 的第二个以及后面参数都会传递给执行的函数
  • this 作为原始值都会被包装

this 作为原始值都会被包装

// 
function print() {
    console.log(typeof this, this)
}

print.bind(1)()
// object Number {1}
print.call(1)
// object Number {1}

call 用作继承使用

function Animal(name, age) {
    this.name = name
    this.age = age
    this.get = function() {
        return 'this is ' + this.name + ', age ' + this.age
    }
    return this
}

Animal.prototype.toYou = function() {
    return 'this is your name ' + this.name
}

function Dog(age){
    Animal.call(this, 'dog', age)
    return this
}

var d = new Dog(8)

d
// Dog {name: "dog", age: 8, get: ƒ}
d.get()
// "this is dog, age 8"

// Animal 的属性都可以被继承,但原型链上的方法不会

// 可以通过追加原型链的继承
Dog.prototype = new Animal()
var d1 = new Dog(9)

d1.toYou()
// "this is your name dog"

bind 函数在用于 new 构造和 直接执行的区别

var eg = { type: 2 }
var Dog = Animal.bind(eg, 'dog')

var d = new Dog(9)
var d1 = Dog(8)

d
// Animal {name: "dog", age: 9, get: ƒ}
d1
// {type: 2, name: "dog", age: 8, get: ƒ}
d.toYou()
// "this is your name dog"
d1.toYou
// undefined

// 直接执行会保留 this,new 构造会忽略 this

相关文章

网友评论

      本文标题:Function call 和 bind 区别?

      本文链接:https://www.haomeiwen.com/subject/ydbbkltx.html