JS 对象创建

版权声明:转载请注明出处 https://blog.csdn.net/nk1212582/article/details/81195329

版权声明:转载请注明出处 https://blog.csdn.net/nk1212582/article/details/81195329

JS中不能定义类,但可以直接创建对象

使用字面量创建对象

JS中的对象属于基本数据类型

对象字面量类似于JSON,采用对象字面量表示的JS对象是一个无序的键值对集合

var Person = {
	name: "Tony",
	age: 18,
	description: function(){
		return this.name + "的年龄是:" + this.age;
	}
}

console.log(Person.description());	//输出为:Tony的年龄是:18
var p1 = Person;					//p1和Person是同一个对象
p1.age = 22;
console.log(Person.description());  //输出为:Tony的年龄是:22

代码中Person就是使用字面量创建的对象,从中可以看出p1和Person是同一对象

使用Object.create()创建对象

使用Object.create()创建对象,可以在原来对象的基础上复制出一个新的对象,采用的复制方式是“深层复制”

var Person = {
	name: "Tony",
	age: 18,
	description: function(){
		return this.name + "的年龄是:" + this.age;
	}
}

console.log(Person.description());	//输出为:Tony的年龄是:18
var p2 = Object.create(Person);
p2.age = 29;
console.log(Person.description());	//输出为:Tony的年龄是:18

代码中p2是使用Object.create()创建对象,从中可以看出p2和Person是不同的对象

var p3 = Object.create({
	name: "Tom",
	age: 30,
	description: function(){
		return this.name + "的年龄是:" + this.age;
	}	
});

console.log(p3.description())	//输出为:Tom的年龄是:30

Object.create()的参数也可采用字面量标识

使用构造函数创建对象

function Student(name, age){
	this.name = name;
	this.age = age;
	this.description = function(){
		return this.name + "的年龄是:" + this.age;
	}
}

var p4 = new Student("Tony", 28);
var p5 = new Student("Tom", 40);
console.log(p4.description())	//输出为:Tony的年龄是:28
console.log(p5.description())	//输出为:Tom的年龄是:40

Student(name, age)就是构造函数

p4、p5是通过构造函数创建的

猜你喜欢

转载自blog.csdn.net/nk1212582/article/details/81195329