牵扯到js函数调用,this指针就不可避免的要涉及,那么this指针到底指向谁,请牢记:“this永远指向当前正在执行的函数对象”,js函数有四种状况,分别是:javascript
NO1:html
<script type="text/javascript"> function test1 (a,b) { console.log(this);//this=>window return document.write(a*b+"<br />"); } test1(2,5);//返回10 var test2 = function (a,b) { console.log(this);//this=>window return document.write(a*b); } test2(2,5)//返回10 </script>
解释说明:针对这种状况,函数自己就是全局对象,而在html中全局对象就是html自己,而在浏览器中页面对象就是浏览器窗口对象(window),因此以上函数会自动成为window对象下的函数java
NO2:浏览器
var objFun = { a:2, b:8, test3:function (a,b) { console.log(this);//this=>object自己 return document.write(a*b+"<br />"); //return document.write(this.a*this.b+"<br />"); } } objFun.test3(2,5);//返回10
解释说明:test3是一个函数(也是objFun的一个方法),函数自己归属于对象(这是由于函数的typeof为function,而function自己就是对象),而objFun是函数的全部者,因此this指向objFun自己函数
NO3:this
function test4 (a,b) { this.first = a; this.second = b; console.log(this);//this=>test4自己 } var x = new test4(2,5);
解释说明:这里使用了new关键字,而new关键字的做用就是从新创建一个对象,因此this指向test4自己,spa
你们也能够试着在控制台打印出他们的typeof结果看一下。指针
转载请注明出处!=>http://www.cnblogs.com/zxn-9588/p/8916152.html code