您的位置:首页 > Web前端 > JavaScript

Javascript学习笔记一 对象

2010-04-13 21:13 661 查看
 检索:

1 用||来填充默认值

var status = flight.status || "unknown";


2 使用&&防止TypeError

flight.equipment.model   //throw "TypeError"

flight.equipment && flight.equipment.model  //undefined


 

引用

var a={},b={},c={};
document.writeln(a===b);  //false


 

原型

Javascript提供的实现机制:

var stooge = {
"first-name":"Jerome",
"last-name":"Howard"
};
var temp = function(){};
temp.prototype=stooge;
var another_stooge= new temp;


可以直接给Object加个方法来简化

if (typeof Object.beget !== 'function'){
Object.beget = function (o){
var F = function (){};
F.prototype = o;
return new F();
}
}

var another_stooge =Object.beget(stooge);
another_stooge["first-name"] = 'Harry';
document.writeln(another_stooge["first-name"]); //Harry
document.writeln(another_stooge["last-name"]);  //Howard
document.writeln(stooge["first-name"]);         //Jerome


 

反射

typeof可以访问原型链

document.writeln(typeof flight.toString); //function


hasOwnProperty则不行

 
document.writeln(flight.hasOwnProperty('toString')); //false


 

枚举

使用for in枚举属性 的顺序是不确定的,而且需要使用hasOwnProperty,并使用typeof排除函数

最好

var properties = [
"first-name",
"last-name"
];

for (var i = 0; i < properties.length; i+=1){
document.writeln(properties[i] + ": " + stooge[properties[i]]);
}


 

删除

删除不会触及原型链,删除对象属性,原型链的属性浮现出来

anothet_stooge["first-name"] = "Jack";
document.writeln(anothet_stooge["first-name"]);//Jack
delete anothet_stooge["first-name"];
document.writeln(anothet_stooge["first-name"]);//Jerome


 

命名空间

var MYAPP= {};
MYAPP.stooge = {
//...
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息