[JavaScript]Functions as Methods

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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值