关于javascript:手写call方法

7次阅读

共计 816 个字符,预计需要花费 3 分钟才能阅读完成。

Function.prototype.myCall = function(content){
  // call 办法如果第一个参数传入  null  this 会指向 window
  content = content || window
  // content.fn = this   // 在这给 content 参数对象增加了一个 fn 的办法  完结后要删除这个办法
  // 要判断这个办法是否曾经存在 所以这个 fn 必须是惟一的
  var  uniqueID = "00" + Math.random();
  // 定义一个随机数
  while (content.hasOwnProperty(uniqueID)) {
    // 如果参数上有这个随机数,就再生成一个
    uniqueID = "00" + Math.random();}
  content[uniqueID] = this


 
  let args = [...arguments].slice(1)
 // 如果 call 办法有返回值  定义这个办法的   而后返回这个后果
  var result = content[uniqueID](...args)

  //  执行完后,要删除这个办法,不扭转传入的参数  
  delete content[uniqueID]
  // 删除之后,原参数就不扭转了
  return result
}



var person = {fullName: function(txt) {console.log(txt + this.firstName + " " + this.lastName);
   }
 }
var person1 = {
   firstName:"John",
   lastName: "Doe"
} 
console.log(person1) //  {firstName: 'John', lastName: 'Doe'}  right
person.fullName.myCall(person1, "Hello,");  // 输入 "Hello, John Doe"
console.log(person1)  // {firstName: 'John', lastName: 'Doe', fn: ƒ}   error

正文完
 0