您的位置:首页 > 移动开发

JavaSrcipt中的call()和apply()方法理解

2016-12-07 22:26 615 查看

call()

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

语法:

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


参数:

thisArg

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

arg1, arg2, …

指定的参数列表。

apply()

apply()方法和call()功能一样,区别在于参数不一样,apply方法只接受一个数组参数

语法:

fun.apply(thisArg[, argsArray])


参数:

thisArg

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

argsArray

一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 fun 函数。如果该参数的值为null 或 undefined,则表示不需要传入任何参数。从ECMAScript 5 开始可以使用类数组对象。浏览器兼容性请参阅本文底部内容

举例:

var animals =
{species: 'Lion', name: 'King'}

function greet() {
var reply = [this.species, 'Is An Awesome', this.name].join(' ');
console.log(reply);
}

greet.call(animals)
greet.apply(animals)


输出效果:



理解:

//上面的代码等同于
var animals = {
species: 'Lion',
name :'King',

}
animals.greety = function () {
var reply = [this.species, 'Is An Awesome', this.name].join(' ');
console.log(reply);
}
animals.greety()


可以按java的继承概念理解:animal对象继承了greet对象的属性和方法,那么animal对象则可以拥有greety对象方法

另一个例子:

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

if (price < 0) {
throw RangeError('Cannot create product ' +
this.name + ' with a negative price');
}
}

//在Food中调用了Pruduct的构造函数,更加形象的说明了继承关系
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}

//等同于
function Food(name, price) {
this.name = name;
this.price = price;
if (price < 0) {
throw RangeError('Cannot create product ' +
this.name + ' with a negative price');
}

this.category = 'food';
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JavaScript Js call apply