apply() & call()

[b]apply & call[/b]

Function 对象 调用 apply(obj,args),call(obj,args) ,就好像 obj 自己拥有了 对应的 Function 对象 一样,

------
[b]apply()[/b]

function.apply(thisobj, args)

invokes the specified function as if it were a method of thisobj, passing it the arguments contained in the args array.
It returns the value returned by the function invocation.
Within the body of the function, the this keyword refers to the thisobj object.

The args argument must be an array or an Arguments object.

Use Function.call( ) instead if you want to specify the arguments to pass to the function individually instead of as array elements.

------
[b]call()[/b]

function.call(thisobj, args...)

only difference to apply() is:
call() accept args individually,
apply() accept args as array or object.

------
[b]例子:[/b]

* [b]js (inherit_test.js)[/b]

/**
* inherit test
*/

/** Fruit class,superclass */
function Fruit(name,description){
this.name = name;
this.description = description;
}
Fruit.prototype.sayHello = function() {
alert('Hello,I am '+ this.name);
};

/** Apple class,subclass */
function Apple(name,description,price){
// 由 Fruit 构造函数调用
Fruit.call(this,name,description);
this.price = price;
}
Apple.prototype.sayHello = function(){
// 由 Fruit.sayHello 函数调用
Fruit.prototype.sayHello.call(this);
};


* [b]html[/b]


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
<script type="text/javascript" src="inherit_test.js"></script>
</head>
<body>
<input type="button" value="hello fruit" onclick="var fru = new Fruit('fruit','');fru.sayHello();" /><br />
<input type="button" value="hello apple" onclick="var ap = new Apple('apple','');ap.sayHello();" /><br />
</body>
</html>


*

------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值