码迷,mamicode.com
首页 > Web开发 > 详细

JS——创建对象

时间:2017-10-18 17:11:24      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:定义   函数   cti   cts   script   title   按钮   一个   object   

创建了对象的一个新实例,并向其添加了四个属性:

person=new Object();//不要var
person.firstname="Bill";
person.lastname="Gates";
person.age=56;
person.eyecolor="blue";

替代代码:

var person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

使用对象构造器:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
var tercher=new person("Bill","Gates",56,"blue");

在构造器函数内部定义对象的方法:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}

调用:

myMother.changeName("Ballmer");

循环遍历对象的属性:

<!DOCTYPE html>
<html>
<body>
<p>点击下面的按钮,循环遍历对象 "person" 的属性。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x;
var txt="";
var person={fname:"Bill",lname:"Gates",age:56}; 

for (x in person)
{
txt=txt + person[x];
}

document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>

结果:BillGates56

参考:JS对象创建JS创建类和对象

JS——创建对象

标签:定义   函数   cti   cts   script   title   按钮   一个   object   

原文地址:http://www.cnblogs.com/wuqiuxue/p/7687603.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!