Function.prototype.call()
call() 方法调用一个函数, 其具有一个指定的this
值和分别地提供的参数(参数的列表)。
注意:该方法的作用和 apply()
方法类似,只有一个区别,就是call()
方法接受的是若干个参数的列表,而apply()
方法接受的是一个包含多个参数的数组。作用:这两个函数都是在特定的作用域中调用函数,能改变函数的作用域,实际上是改变函数体内 this 的值 。
使用call
方法调用父构造函数
在一个子构造函数中,你可以通过调用父构造函数的call
方法来实现继承,类似于Java
中的写法。下例中,使用Food
和Toy
构造函数创建的对象实例都会拥有在Product
构造函数中添加的name
属性和price
属性,但category
属性是在各自的构造函数中定义的。
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
使用call
方法调用函数并且指定上下文的'this
'
在下面的例子中,当调用greet
方法的时候,该方法的this
值会绑定到obj
对象。
function greet() {
var reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
console.log(reply);
}
var obj = {
animal: 'cats', sleepDuration: '12 and 16 hours'
};
greet.call(obj); // cats typically sleep between 12 and 16 hours
首先必须要说的是,this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁
实际上this的最终指向的是那个调用它的对象
demo1:
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //12
}
}
}
o.b.fn();
demo2:
var o = {
a:10,
b:{
// a:12,
fn:function(){
console.log(this.a); //undefined
}
}
}
o.b.fn();
demo3:
var o = {
user:"bianbumei",
fn:function(){
console.log(this.user); //bianbumei
}
}
window.o.fn();
demo4:
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //undefined
console.log(this); //window
}
}
}
var j = o.b.fn;
j();
理解方法:
猫吃鱼,狗吃肉,奥特曼打小怪兽。
有天狗想吃鱼了
猫.吃鱼.call(狗,鱼)
狗就吃到鱼了
猫成精了,想打怪兽
奥特曼.打小怪兽.call(猫,小怪兽)