JavaSrcipt中的call()和apply()方法理解
来源:互联网 发布:小米网上商城软件下载 编辑:程序博客网 时间:2024/05/16 16:15
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'; }
0 0
- JavaSrcipt中的call()和apply()方法理解
- JavaScript 中的 call() 和 apply() 方法深入理解
- 【JavaScript 学习--09】--理解Js 中的apply 和 call方法
- 理解JS中的call、apply、bind方法
- 理解JS中的call、apply、bind方法
- 理解JS中的call、apply、bind方法
- 理解JS中的call、apply、bind方法
- 理解JavaScript中的this、call和apply
- 如何理解js中的call和apply
- Javascript:apply()和call()方法深入理解
- JavaScript中的apply()方法和call()方法
- javascript中的call方法和apply方法
- JS中的apply方法和call方法
- js 中的 call() 方法 和 apply()方法
- JavaScript中的apply()方法和call()方法
- JavaScript中的call方法和apply方法
- javascript中的call和apply方法
- js中的call()和apply()方法
- CSS三栏布局的四种方法
- 使我的设备支持全Linux环境(解决设备的linux命令不全的问题)
- JSP中的四大作用域:page、request、session、application
- postgresql 内核开发之系统参数增加(下)
- 以"慕课网"为例使用nodeJS爬取动态网页中的动态数据
- JavaSrcipt中的call()和apply()方法理解
- 总结68
- 《算法概论》第八章习题 8-15
- javascript事件, 解决mousedown和click冲突事件, 鼠标事件, 键盘事件, 文本事件用法简介
- kvm:linux的虚拟机监控器(kvm: the Linux Virtual Machine Monitor)
- 金牌 银牌 铜牌
- python中基于descriptor的一些概念 新式类 旧式类
- 系统编程中的文件大小修改truncate/lseek
- Gradle命令编译Android项目