function
1、 function就是数据值(data values)
2、 定义此 function 的名字没有任何特殊之处
3、 可以将 function 分配给任何 variable 或者 某对象的任何一个 property
method
1、 method 仅仅也就是一个JavaScript function,没有任何特殊之处
2、 此 JavaScriptfunction 存储在一个对象的 property 中
3、 当调用此 JavaScriptfunction 时,要通过此对象来调用
假设,对象 ob j有一个 method m,则我们可以这样调用
obj.m(arg1, arg2, arg3);
注意:当调用某个method时,实际上,隐含地传递了obj 到此 method 中(method体内,this就指向此obj)
1、 在method体内部,this关键字的值就是这个对象(即obj)
2、 在method体内部,你可以通过this关键字来得到这个对象(即obj)(这里的 1, 2没啥区别,都是同样的意思)
var calculator = { // An object literal operand1: 1, operand2: 1, compute: function() {//注意:这里的 function 没有定义名称 this.result = this.operand1 + this.operand2; // this 关键字就指向对象本身 (即calculator) } }; calculator.compute(); // What is 1+1? print(calculator.result); // Display the result |
this 关键字 到底指向谁?
1、 当 function 被作为函数而调用时,this 关键字 指向 global object
2、 在 method体内,this 关键字 指向此 method 的对象
3、method 的内部的 nested function中,this 关键字 也是指向 global object(同1)
<html>
<head>
<script type="text/javascript">
var myObj = {
objMethod: function(){
alert("I'm myObj.objMethod method, this keyword points to myObj");
alert(this);//myObj
return function(){
alert("I'm myObj.objMethod's nested method, this points to global object");
alert(this);//global object
};
}
}
function pureFunction(){
alert("I'm pureFunction, and this keyword points to global object");
alert(this);//global object
}
function functionAsMethod() {
myObj.objMethod()();
pureFunction();
}
</script>
</head>
<body>
<form>
<input type="button" name="demojavascript" value="Demo Function as Methods"
οnclick="functionAsMethod();"/>
</form>
</body>
</html>