qwe*_*ymk 2 javascript replace reference call
为什么这是有效的:
function func(a,b,c) {
console.log(this, a,b,c);
return '';
}
'testing'.replace(/e/, func);
Run Code Online (Sandbox Code Playgroud)
但这不是:
function func(a,b,c) {
console.log(this, a,b,c);
return '';
}
'testing'.replace(/e/, func.call);
Run Code Online (Sandbox Code Playgroud)
如果func是一个函数引用,并且call是函数引用,那么它们是否都可以工作?
这里有一个小提琴的这
因为当你传递call功能,你把它拿出来的背景下func,这样里面call的this关键字将引用window代替func.
window不是一个函数,但call希望this是一个函数,所以它打破了.
为了比较.
var AnObject = {
call: function () { console.log("this.location is: ", this.location); },
location: "This string is the location property of AnObject"
};
AnObject.call();
setTimeout(AnObject.call, 500);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
324 次 |
| 最近记录: |