Heim  >  Artikel  >  Web-Frontend  >  Javascript中的call()方法介绍_javascript技巧

Javascript中的call()方法介绍_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:09:231146Durchsuche

在Mozilla的官网中对于call()的介绍是:

复制代码 代码如下:

call() 方法在使用一个指定的this值和若干个指定的参数值的前提下调用某个函数或方法.

Call() 语法
复制代码 代码如下:

fun.call(thisArg[, arg1[, arg2[, ...]]])

Call() 参数

thisArg

复制代码 代码如下:

在fun函数运行时指定的this值。需要注意的是,指定的this值并不一定是该函数执行时真正的this值,如果这个函数处于非严格模式下,则指定为null和undefined的this值会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象。

arg1, arg2, ...
复制代码 代码如下:

指定的参数列表。

Javascript中的call()方法

先不关注上面那些复杂的解释,一步步地开始这个过程。

Call()方法的实例

于是写了另外一个Hello,World:

复制代码 代码如下:

function print(p1, p2) {
    console.log( p1 + ' ' + p2);
}
print("Hello", "World");
print.call(undefined, "Hello", "World");

两种方式有同样的输出结果,然而,相比之下call方法还传进了一个undefined。

接着,我们再来看另外一个例子。

复制代码 代码如下:

var obj=function(){};
function print(p1, p2) {
    console.log( p1 + ' ' + p2);
}

print.call(obj, "Hello", "World");

只是在这里,我们传进去的还是一个undefined,因为上一个例子中的undefined是因为需要传进一个参数。这里并没有真正体现call的用法,看看一个更好的例子。

复制代码 代码如下:

function print(name) {
    console.log( this.p1 + ' ' + this.p2);
}

var h={p1:"hello", p2:"world", print:print};
h.print("fd");

var h2={p1:"hello", p2:"world"};
print.call(h2, "nothing");

call就用就是借用别人的方法、对象来调用,就像调用自己的一样。在h.print,当将函数作为方法调用时,this将指向相关的对象。只是在这个例子中我们没有看明白,到底是h2调了print,还是print调用了h2。于是引用了Mozilla的例子

复制代码 代码如下:

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

    if (price         throw RangeError('Cannot create product "' + name + '" with a negative price');
    return this;
}

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

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


在这里我们可以真正地看明白,到底是哪个对象调用了哪个方法。例子中,使用Food构造函数创建的对象实例都会拥有在Product构造函数中添加的 name 属性和 price 属性,但 category 属性是在各自的构造函数中定义的。

复制代码 代码如下:

function print(name) {
    console.log( this.p1 + ' ' + this.p2);
}

var h2= function(no){
    this.p1 = "hello";
    this.p2 = "world";
    print.call(this, "nothing");
};
h2();

这里的h2作为一个接收者来调用函数print。正如在Food例子中,在一个子构造函数中,你可以通过调用父构造函数的 call 方法来实现继承。

至于Call方法优点,在《Effective JavaScript》中有介绍。

1.使用call方法自定义接收者来调用函数。
2.使用call方法可以调用在给定的对象中不存在的方法。
3.使用call方法可以定义高阶函数允许使用者给回调函数指定接收者。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn