请问js中call与apply区别?
网友回复
在回答你的问题之前,我们想理解一下js中this关键字
在面向对象语言中 this 表示当前对象的一个引用。
但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。
在方法中,this 表示该方法所属的对象;
如果单独使用,this 表示全局对象;
在函数中,this 表示全局对象;
在函数中,在严格模式下,this 是未定义的(undefined);
在事件中,this 表示接收事件的元素。
那么call() 和 apply() 方法可以将 this 引用到任何对象。
apply 和 call 允许切换函数执行的上下文环境(context),即 this 绑定的对象,可以将 this 引用到任何对象。
先看看call的写法:<script type="text/javascript"> var person1 = { fullName: function() { return this.firstName + " " + this.lastName; } } var person2 = { firstName: "John", lastName: "Doe", } /*console.log(person1.fullName.apply(person2)); // 返回 "John Doe"*/ console.log(person1.fullName.call(person2)); // 返回 "John Doe" </script>
使用 person2 作为参数来调用 person1.fullName 方法时, this 将指向 person2, 即便它是 person1 的方法。
在看看call()的另外一种用法:<script type="text/javascript"> function person1(name, age) { this.name = name; this.age = age; } function person2(name, age, grade) { person1.call(this, name, age); this.grade = grade; } var person = new person2("xiaoming", 20, "dasan"); console.log(person.name+person.age+person.grade); ...
点击查看剩余70%