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'; }
相关文章推荐
- JavaSrcipt获取HtmlStyle属性兼容方法
- 理解JS中的call、apply、bind方法
- javasrcipt实现简单UBB代码方法
- 彻底理解了call()方法,apply()方法和bind()方法
- 《学习日记》prototype,_proto_以及call\apply方法理解
- Javascript:apply()和call()方法深入理解
- javasrcipt 常用属性,方法
- 深入理解关于javascript中apply()和call()方法的区别
- JavaScript之call(),apply(),bind()三个方法理解
- 深入理解关于javascript中apply()和call()方法的区别
- 谈谈关于js中关于函数的apply和call方法的理解
- JavaSrcipt的三种函数定义方法
- 理解JS中的call、apply、bind方法
- javasrcipt 常用属性,方法
- 深入理解JavaScript中的call、apply、bind方法的区别
- 理解JS中的call、apply、bind方法
- 关于JAVASRCIPT的方法的参数
- 【JavaSrcipt】substring方法小解析
- 理解JS中的call、apply、bind方法