JavaScript之This及Array-like Object乱谈

看到论坛中有如下代码引起的关于this的一个讨论,下面做些相关的“杂说”
先看那段代码:
var theMonths = new MakeArray(12);
function MakeArray(n) {  
   this[0] = "January"; 
   this[1] = "February";
   this[2] = "March"; 
   this[3] = "April"; 
   this[4] = "May"; 
   this[5] = "June"; 
   this[6] = "July"; 
   this[7] = "August"; 
   this[8] = "September";
   this[9] = "October"; 
   this[10] = "November"; 
   this[11] = "December";
   this.length = n;
   return this; 
}
开始乱讲:::
这里定义了一个方法,名字是MakeArray(之所以没说定义了一个对象,是因为它带有return this),
这样理解不知是否说的过去,该方法所做的就是产生一个Array-like Object;我们注意到它生成的
对象具有属性[0...11]和length,之所以说他是Array-like的是因为我们可以使用
function's arguments is an array-like object
for(var i =0;i<length;i++){
  //code
}
来访问它的属性元素,
如果我们使用下面的代码:
for(var p in theMonths){
//print p;我们可以得到结果:0...11和length;
}
只要我们不试图打乱length属性的含义,我们可以使用它就象使用数组一样。
下面再来看一些相关方面的定义:
1::::::加入属性
var array_like = {};
var index = 1;
for(;index<=6;index++){
   array_like = index;//[1,2,3,4,5,6]
}
array_like.length = 6;//[6=1+2+3];是一个完全数,因此我喜欢使用它
2::::::使用this
var mm = this[0] = "aa";
如果作为一道测试题,估计挂的十有八九。
3::::::使用this
function makeFunction(){
   this[0] = function(){};
   this[1] = function(){return "function";}
}
var fun_hand = new makeFunction();
alert(fun_hand[1]());//fun_hand[1]() <==> var _hand = fun_hand[1];_hand();
4:::::::
关于Copying 而不是Referring
function noticeThekeyOfThis(){
   this.name = "the property of this object.";
   return this;
}
我们为定义的对象增加name 属性:
var myobj = new noticeThekeyOfThis();
alert(myobj.name);
------
另一个例子:
<div id="divId" οnmοuseοver="showName(obj)">(28=1+2+4+7+14)</div>
function noticeThis(){
  //alert("call");
  this.myproperty = "name of this";
}
document.getElementById("divId").onclick = noticeThis;
function showName(obj){
  alert(obj.myproperty);
}
这里只是一些相关信息的杂烩,如果需要真的掌握这些,可搜索Array-like object 来自己研究
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值