1.封装函数 f,使 f 的 this 指向指定的对象

封装函数 f,使 f 的 this 指向指定的对象

解析:此题考查call,apply,bind()的用法,这三个api都可以实现改变this指向。

区别在于
f.call(obj, arg1, arg2...),参数是直接按顺序写进去的
f.bind(obj, arg1, arg2,...)(),参数同call写法一样,不同于call的地方是在于f.bind返回的是一个函数
f.apply(obj, [arg1, arg2, .]),参数是以数组传入;

例子:apply

var person = {
  fullName: function(city, country) {
      console.log(this.firstName + " " + this.lastName + "," + city + "," + country)
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"John",
  lastName: "Doe"
}
let a = person.fullName.apply(person1, ["Oslo", "Norway"]);
console.log(a)

运行结果:

 

 call例子;

var person = {
  fullName: function(city, country) {
      console.log(this.firstName + " " + this.lastName + "," + city + "," + country)
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"John",
  lastName: "Doe"
}
let a = person.fullName.call(person1, "Oslo", "Norway");
console.log(a)

运行结果:

bind例子:

var person = {
  fullName: function(city, country) {
      console.log(this.firstName + " " + this.lastName + "," + city + "," + country)
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"John",
  lastName: "Doe"
}
let a = person.fullName.bind(person1, "Oslo", "Norway");
let b = a()
console.log(a)

运行结果:

 

 

题目要我们封装一个函数f,所以我们可以重新生成一个函数返回出去。所以题目答案为:

1.apply解

function bindThis(f, oTarget) {
 return function() {
     return f.apply(oTarget, arguments)
 }
}

2.bind解

function bindThis(f, oTarget) {
 return f.bind(oTarget)
}

3.call解

function bindThis(f, oTarget) {
 return function() {
     return f.call(oTarget, ...arguments)
 }
}

 

posted @ 2021-05-20 16:06  Origin-666  阅读(187)  评论(0)    收藏  举报