首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

call跟apply到底有啥用

2012-10-08 
call和apply到底有啥用? ? ?为什么有这两个函数呢?们到底可以做什么?mozilla官方的文档让我看到了一点端倪

call和apply到底有啥用

? ? ?为什么有这两个函数呢?们到底可以做什么?


mozilla官方的文档让我看到了一点端倪:

1、call函数可以让你从已有的对象中继承一个方法,而不必为新对象写一个新的方法

With call, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
function Product(name, value){ this.name = name; if(value >= 1000) this.value = 999; else this.value = value;} function Prod_dept(name, value, dept){ this.dept = dept; Product.call(this, name, value); //这里this对象调用Product方法,以帮助实现Prod_dept方法。} Prod_dept.prototype = new Product(); cheese = new Prod_dept("feta", 5, "food");car = new Prod_dept("honda", 5000, "auto");?今天我又看到了一个call的用途

2、明确指出函数调用的上下文。

没错,有时候在函数调用的过程中,转来转去常常会让this迷失方向,call和apply函数则可以明确指出此函数调用的this对象是谁。

? ? ? ? 例子如下:

?

var first_object = {num: 42};var second_object = {num: 24};function multiply(mult) {return this.num * mult;}multiply.call(first_object, 5); // 返回 42 * 5multiply.call(second_object, 5); // 返回 24 * 5

热点排行