【前端学习笔记】JS创建对象的方式

215 阅读2分钟

Object构造函数模式

var obj = new Object();
obj.id = '01';
obj.nickname = 'CRR';
obj.sayName = function (){
	console.log(this);//{id:'01',nickname:……}
	console.log(this.nickname);
}

obj.sayName();
console.log(obj.id);//01

对象字面量模式-最简单

var obj = {
	id: '02',
	nickname: 'XXD',
	sayName: function(){
	  console.log(this);
	  //{id: "02", nickname: "XXD", sayName: ƒ}
	  console.log(this.nickname);
	}
}
obj.sayName();

工厂模式-返回对象字面量

也可以说是利用函数去构造对象,函数就相当于工厂一样。 优点:解决了创建多个相似对象的问题,函数封装创建对象,无需写重复创建对象的代码。 缺点:没有解决对象识别的问题(怎么样知道一个对象类型)

function createObj(name,age,job){
	let o = new Object();
	o.name = name;
	o.job = job;
	o.age = age;
	o.sayName = function(){
    	console.log(this.name);
	}

	return o;
}

let obj1 = createObj('CRR',24,"dancer");
let obj2 = createObj('XXD',24,"engineer");

构造函数模式

function Person(name,age){
	console.log(this);//Person
	this.name = name;
	this.age = age;
	this.sayName = function(){
		console.log(this.name);
	}
}
let person1 = new Person('CCR',21);//这里是new
let person2 = new Person('XXD',22);
console.log(person2.name);

要创建person的新实例,必须使用new操作符,经历一下四个步骤

  • 创建一个新对象
  • 将构造函数的作用域付给了新对象(因此this指向了这个新对象)
  • 执行构造函数的代码(为这个新对象添加属性)
  • 返回新对象

原型创建对象

function Person(){}
Person.prototype = {
	constructor : Person,
	name: "CRR",
	age: 24
};

var person1 = new Person();
console.log(person1._proto_);

01

构造函数加原型链-认可度最多

function Person(name,id){
	this.name = name;
	this.id = id;
	//
	this.sex = 'girl';
}

Person.prototype = {
	constructor: Person,
	sayName: function(){
		//
		console.log(this.name);
	}
}
var person1 = new Person('CCC',21);
var person2 = new Person('XXX',23);
person1.sex = 'boy';
console.log(person1.sex); //boy
console.log(person2.sex); //girl
person1.sayName();//CCC

寄生式继承=使用共享方法 和 Object.create 的函数实例化

参考:juejin.cn/post/684490… 由于 child 是用 object.create(parent) 创建的,所以每当child 对象上的属性查找失败时,JavaScript 就会将该查找委托给 parent 对象。

    const Parent = {
	    name: 'father',
    	age: '22',
    	height: '170'
	}
	const child = Object.create(Parent);
	child.name = 'CCC';
	child.age = 24;
	console.log(child);//{name: "CCC", age: 24}
	console.log(child.height);//170

ES6 class继承

    class Parent{
	    constructor(x,y){
	        this.x = x;
	        this.y = y;
	    }

	    toString(){
	    return this.x+' '+this.y;
	    }
	}
	class Child extends Parent{
	    constructor(x,y,color){
	        super(x,y);//注意这里的super
	        this.color = color;
	    }
	    toString(){
	        return this.color+' '+super.toString();
	    }
	}

	let child1 = new Child('1','2','red');
	console.log(child1.toString()); //red12