JavaScript apply()与call()函数

apply和call方法允许一个对象调用不属于自己的方法

例:

let person = {
    
    
  f: function () {
    
     return this.firstname + ' ' + this.lastname }
}

let man = {
    
    
  firstname: 'John',
  lastname: 'Smith'
}

console.log(person.f.apply(man)) // John Smith

上面的例子中,函数 f 不属于man,但是却输出了man中的属性,说明 f 方法内的 this 指向了man。

如果函数需要传参呢?

例:

let person = {
    
    
  f: function (city, country) {
    
     return this.firstname + ' ' + this.lastname + ' ' + city + ' ' + country }
}

let man = {
    
    
  firstname: 'John',
  lastname: 'Smith'
}

console.log(person.f.apply(man, ['潍坊市', '中国'])) // John Smith 潍坊市 中国

apply会接受一个数组进入函数,而call接受的是多个参数:
console.log(person.f.call(man, '潍坊市', '中国'))

如果第一个参数不是对象呢?
在严格模式下,会变成被调用函数的拥有者对象,在非严格模式下会变成全局对象(实际上,传入null/undefined时会变成全局对象,如果传入字符串或者数值的话this还是会指向[String: string]或[Number: 10] // 在非严格模式下)


今天才发现Generator跳了一章没学。。。明天补一补

猜你喜欢

转载自blog.csdn.net/weixin_45543674/article/details/118713953