首页 > 语言 > JavaScript > 正文

Javascript中的call()方法介绍

2024-05-06 14:44:40
字体:
来源:转载
供稿:网友

在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 < 0)
        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 属性是在各自的构造函数中定义的。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选