分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

JS——创建对象

发布时间:2023-09-06 01:18责任编辑:赖小花关键词:暂无标签

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

person=new Object();//不要varperson.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——创建对象

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved