[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]
* [b]html[/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>
*
------