JS创建对象

1.直接定义并创建对象

//定义并创建对象
var person = new Object();
//通过为对象赋值,向已有对象添加新属性
person.firstname = "Bill";
person.lastname =  "skye";
person.age = 18;
//向已有对象添加方法
person.mothod = function(){
    return person;
}
document.writeln(person.firstname + " is " + person.age + " years old.");
document.writeln(JSON.stringify(person.mothod()));

结果图:

或:

var student = {
				"firstname":"Bill",
				"lastname":"skye",
				"age":"19",
				"sex":"girl"
			};
//或者
//var student = {
//				firstname:"Bill",
//				lastname:"skye",
//				age:"19",
//				sex:"girl"
//			};
document.writeln(student.firstname + " is a " + student.sex);

结果图:

或定义一个构造函数,然后在构造函数的原型中添加属性和方法

var teacher = function(){};
teacher.prototype  = {
    //属性
	name:"lin",
	age:23,
	//方法
	getage:function(){
		return "getage";
	}
}
var oneteacher = new teacher();
document.writeln(oneteacher.name + " is " + oneteacher.age + " years old.");
document.writeln(oneteacher.getage());

2.使用对象构造器来构造对象

function person(firstname,lastname,age)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
//定义对象的方法
this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}
myFather=new person("Bill","Gates",56);
document.write(myFather.firstname + " is " + myFather.age + " years old.");
myFather.changeName("Ballmer");

结果图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值