prototype与几个循环的心得

《一》prototype
prototype其实是函数的一个属性,并且只有函数有这个属性,这个属性就是给函数增加函数或者属性的,比如写一个
function one(){},那么one.prototype的类型就是一个对象,使用JSON.stringify(one.prototype)得到的就是一个字符串类型的{}了,显然是一个空的对象。
我添加一个name属性试试,one.prototype.name="这是文本",再JSON.stringify(one.prototype)得到:{‘name’:'这是文本'}。
一个函数其实也是可以变成一个对象的,通过new 函数名 变成对象,这样就可以访问函数里边的对象或者属性了。
我来举个函数添加属性和函数的例子:
function one(){
this.index=1;
}
one.prototype.two=function(e){
return this.index;//返回one里边的index值1,这里的this是one
//return {value:this.index,name:e}//返回的是一个对象
}
var test=new one();//函数对象化
test.hasOwnProperty('index')//判断是否有index这个属性
test;//object{index:1,prototype:two}
test.index;//1
test.two;//返回two函数
test.two();//返回运行后的函数结果,里边是this.index值为1

还有一种写法,是对one进行扩展的,如下:
function one(){
this.index=1;
}
one.prototype=function(){
describe:'version1',
two:function(){//因为two在这里是种对象里的方法,所以写成这样,很多封装好的库里都是这样,比如jQuery
return this.index;
}
}
var test=new one();
test.two();
《二》循环遍历
这个遍历数组或者对象,首先得到的是索引或者是key值,比如
var arr=[3,4,1];
for(var index in arr){
console.log(index)//1,2,3
console.log(arr[index])//3,4,1
}
var obj={name:'wang',age:11};
for(var index in obj){
console.log(index);//name,age
console.log(obj(index);//wang,11
}
而of是直接获取值了。
再补充其他几种循环遍历的方法:

数组原生具备iterator接口(即默认部署了Symbol.iterator属性),for...of循环本质上就是调用这个接口产生的遍历器,可以用下面的代码证明。

const arr = ['red', 'green', 'blue']; for(let v of arr) { console.log(v); // red green blue } const obj = {}; obj[Symbol.iterator] = arr[Symbol.iterator].bind(arr); for(let v of obj) { console.log(v); // red green blue } 

上面代码中,空对象obj部署了数组arrSymbol.iterator属性,结果objfor...of循环,产生了与arr完全一样的结果。

for...of循环可以代替数组实例的forEach方法。

const arr = ['red', 'green', 'blue']; arr.forEach(function (element, index) { console.log(element); // red green blue console.log(index);  // 0 1 2 }); 

JavaScript 原有的for...in循环,只能获得对象的键名,不能直接获取键值。ES6 提供for...of循环,允许遍历获得键值。

var arr = ['a', 'b', 'c', 'd']; for (let a in arr) { console.log(a); // 0 1 2 3 } for (let a of arr) { console.log(a); // a b c d } 

上面代码表明,for...in循环读取键名,for...of循环读取键值。如果要通过for...of循环,获取数组的索引,可以借助数组实例的entries方法和keys方法(参见《数组的扩展》一章)。

for...of循环调用遍历器接口,数组的遍历器接口只返回具有数字索引的属性。这一点跟for...in循环也不一样。

let arr = [3, 5, 7]; arr.foo = 'hello'; for (let i in arr) { console.log(i); // "0", "1", "2", "foo" } for (let i of arr) { console.log(i); // "3", "5", "7" } 

上面代码中,for...of循环不会返回数组arrfoo属性。

参考“https://www.cnblogs.com/loveyoume/p/6112044.html”

转载于:https://www.cnblogs.com/sweeeper/p/8681583.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值