JavaScript学习摘入

2017-01-23  本文已影响0人  陈定邦

-## 1. scope:

2.this的理解:

图解Javascript this指向什么.png
当前对象的例子:
var point = { 
       x : 2, 
       y : 2, 
       moveTo : function(x, y) { 
       this.x = this.x + x; 
       this.y = this.y + y; 
       console.log(this.x);
       console.log(this.y)
   } 
};
point.moveTo(1,1); //this 绑定到当前对象,即point对象`  


全域变量的例子:
function func(x) { 
 this.x = x; 
} 
func(5); //this是全局对象window,x为   全局变量
//决策树解析:func()函数是用new进行调用的么?为否,进入func()函数是用dot进行调用的么?为否,则 this指向全局对象window
x;//x => 5

3.call & apply:

call 跟 apply 隶属于

Function.prototype

所谓的Function.prototype是指Function类型中原生的方法,在ECMAScript标准的第一个版本中就已经初步定义过,所以不用担心兼容性的问题。

call 跟 apply的方法要实现的功能几乎一致,在更改this的指向的情况下,使用某个value或者function。

语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
语法:apply([thisObj[,argArray]])

Example:

var point = { 
 x : 2, 
 y : 2, 
 moveTo : function(x, y) { 
     this.x = this.x + x; 
     this.y = this.y + y; 
     console.log(this.x);
     console.log(this.y)
   } 
 };
point.moveTo(1,1); //this 绑定到当前对    象,即point对象
var point2 = { x:10 , y:10 };
console.log(point2.x);
console.log(point2.y);
point.moveTo.call(point2,3,3);
point.moveTo.apply(point2,[-3,-3]);

Paste_Image.png

这里可以看到通过call和apply来呼叫了point中的内建function->moveTo。需要注意的是这里对于this的指向。

notice
 var testarray = [1,2,3,4];
 console.log(testarray.length);
 testarray['a'] = "hello";
 console.log(testarray.length);
 console.log(testarray['a']);

在使用数组的时候要注意,关联式数组并不会计算入传统的数组结构中。
如上面输出结果,length始终都是4,并不会因为加入了a这个关联式的内容增加。

内容参考

http://www.jianshu.com/p/c6cb7068bb85 【JavaScript】call与apply兄弟列传
http://www.jianshu.com/p/de47c2f9d178 图解Javascript this指向什么?

上一篇 下一篇

猜你喜欢

热点阅读