美文网首页
12,手写一个call

12,手写一个call

作者: r8HZGEmq | 来源:发表于2020-06-11 15:48 被阅读0次
Function.prototype.myCall = function(context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  context = context || window
  context.fn = this
  const args = [...arguments].slice(1) // arguments是Function里的属性
  const result = context.fn(...args)
  delete context.fn
  return result
}

        var color = 'red';// (或者window.color='red')
        document.color = 'yellow';
        var s1 = {color: 'blue', field1: 'aa', field2:'bb'};
        function changeColor(param1){
            console.log(this.color + '---' + param1);
        }
        
        changeColor.myCall(s1, 'helloworld');       //blue

相关文章

网友评论

      本文标题:12,手写一个call

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