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

javascript入门笔记(4)——对象

2015-08-18 10:35 501 查看

Object

Object
operator
delete

traverse all atrributes

Construction

prototype object
problems

solution



like pairs of key:value

var o = new Object();
var circle = {x:0,y:0, radius:2};


operator

you can dynamically add more attributes and child objects!

var book = new Object();
book.title = "html study";
//you can dynamically add more attributes and child objects!
book.chapter1 = new Object();
book.chapter1.title = "html introduction";


delete

delete book.chapter1;
book.chapter1 = null;


traverse all atrributes

for( var x in o)…

var o = new Object();
o.name = "john";
o.age = "56";
for(var x in o){
alert(o[x]);//john,56
alert(x);//name,age
alert(x.valueOf());//name,age
alert(o.x);//undefined. cuz o doesn't have x attribute
}


Construction



Attention:

this.area = function(){ return this.width*this.height;
}


if you change it like this:

this.area= function(){
return w*h;
}


there could be a problem.

eg:

var r = new Rect(5,10);
r.width = 10;
alert(r.area());//this must update with width


prototype object

shared attribute

function Person(){
Person.prototype.name = "jane";

};
var p1 = new Person();
var p2 = new Person();
p1.name = "john";// assignment
alert(p1.name);//john (from instance)
alert(p2.name);//jane (from prototype)


problems



if the attribute is an array, the push() action will affect all the objects.

solution:

combine prototype and regular construction.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: