js call方法

call方法做什么用的?

javascript 中关于call方法的详解。 - 追逐云端 - 博客园

指定this指针

The call() method calls a function with a given this value and arguments provided individually.
如下,test函数,如果调用的话。this是谁呢?可以使默认值,如果你想传入一个特定的this呢?
就要用call方法。

function test(){
    alert(this);
    alert(this.name);
    alert(this.age)
};


var lisi= {name: "李四", age: 20};
// 更改内部的this指针引用对象为obj
test.call(lisi); // [object Object] 李四 20

简而言之,就是给this指定值(对象)的。

指定this的同时给函数传入一些参数

如下
Product.call(this, name, price);
这一句

function test(a,b){
    alert(this);
    alert(a+b)
};


var lisi= {name: "李四", age: 20};
// 更改内部的this指针引用对象为obj
test.call(lisi,2,3); // [object Object] 5

实现类的继承

function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

var cheese = new Food('feta', 5);

alert(cheese.name);//feta
alert(cheese.price);//5
alert(cheese.category);//food

总结,这两个功能好像没啥联系

dodge!

参考

Function.prototype.call() - JavaScript | MDN
JavaScript Function.call() 函数详解 - CodePlayer
javascript 中关于call方法的详解。 - 追逐云端 - 博客园
call 方法 (Function) (JavaScript)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容