js call() & apply()用法初阶

98 阅读1分钟

使用js call()语法

  • call()功能是改变函数的调用对象。

如:

(
    function testFn(){
        let name = "药尘";
        let obj = {
            name:"萧薰儿",
            test:{
                    name:"萧炎",
                    e:function (){
                        debugger;
                        name:"萧炎";
                        console.log(this.name);
                        console.log(name+"test");
                }
            }
        }
        obj.test.e();
        obj.test.e.call(obj);
        // obj.test.e.call();
    }
)();
// 打印结果:
//萧炎
//药尘test
//萧薰儿
//药尘test

结论:使用call的参数能将this的指代替换。