JavaScript之call模拟实现javascript
var obj = { value : 1 } function foo(){ console.log(this.value) } foo.call(obj)
注意:java
var obj = { value :1, foo : function(){ console.log(this.value) } } obj.foo()
这个时候this就指向了obj数组
以上个例子为例,就是:函数
// 第一步 obj.fn=foo // 第二步 obj.fn() // 第三步 deleteobj.fn
按照这个思路,尝试写初版call2函数this
Function.prototype.call2 = function(context){ context.fn=this context.fn() delete context.fn } var obj = { value : 2 } function foo(){ console.log(this.value) } foo.call2(obj)
var obj = { value : 1 } function foo(name,age){ console.log(name)// hy console.log(age)// 18 console.log(this.value)// 1 } foo.call(obj,'hy',18)
注意: 传入的参数不肯定,该怎么办!spa
var args = [] for(let i=1; i<arguments.length; i++) { args.push('arguments['+i+']'); }
不定长的参数问题解决了,咱们接着要把这个参数数组放到要执行的函数的参数里面去。prototype
eval('context.fn('+ args +')')
第二版代码以下:code
Function.prototype.call2 = function(context){ context.fn=this var args = [] for(let i=1; i<arguments.length; i++) { args.push('arguments['+i+']'); } eval('context.fn('+args+')'); delete context.fn } var obj = { value :2 } function foo(name,age){ console.log(name) console.log(age) console.log(this.value) } foo.call2(obj,'hy',18)
模拟实现第三步对象
var value = 1 function foo(){ console.log(this.value) } foo.call(null)// 1
2. 函数是能够有返回值的ip
var obj = { value :1 } function foo(name,age){ return{ value : this.value, name : name, age : age } } console.log(foo.call(obj,'hy',18))// { value: 1, name: 'hy', age: 18 }
到目前为止已经完成了 call 的模拟
Function.prototype.call2 = function(context){ context.fn=this var args = [] for(leti=1;i<arguments.length;i++) { args.push('arguments['+i+']'); } var result = eval('context.fn('+args+')'); delete context.fn return result } var obj = { value : 2 } function foo(name,age){ return{ value : this.value, name : name, age : age } } console.log(foo.call2(obj,'hy',18))