Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript创建对象的多种方式及优缺点(7种) #7

Open
GGXXMM opened this issue Aug 4, 2019 · 0 comments
Open

JavaScript创建对象的多种方式及优缺点(7种) #7

GGXXMM opened this issue Aug 4, 2019 · 0 comments
Labels
⭐️ js js knowledge

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Aug 4, 2019

1、Object构造函数创建

var Person = new Object();
Person.name = 'lisi';
Person.age = 20;

2、使用对象字面量方式创建

var Person = {};
Person = {
  name: 'lisi',
  age: 20
}

优点:上面2种方式,使用较为简单
缺点:上面2种方式,在需要创建很多对象时会产生大量重复代码。

3、Object.create()

var Person = {
  name: 'lisi',
  age: 20
}
var p = Object.create(Person)// 基于Person对象为原型创建对象
var p1 = Object.create(null)// 创建原型为null的原始空对象

4、使用工厂模式创建

function createPerson(name, age, job) {
	var o = new Object();
	o.name = name;
	o.age = age;
	o.job = job;
	o.sayName = function() {
		console.log(this.name)
	}
	return o;
}
var person1 = createPerson('zhangsan', 26, 'teacher');
var person2 = createPerson('lisi', 20, 'student');

缺点:对象无法识别,因为所有的实例都指向一个原型

5、使用new操作符,通过构造函数创建

function Person(name, age, job) {
	this.name = name;
	this.age = age;
	this.job = job;
	this.sayName = function() {
		console.log(this.name);
	}
}
var person1 = new Person('zhangsan', 26, 'teacher');
var person2 = new Person('lisi', 20, 'student');

优点:实例可以识别为一个特定的类型
缺点:每次创建实例时,每个方法都要被创建一次

6、使用原型创建

function Person(){}
Person.prototype.name = 'Nike';
Person.prototype.age = 20;
Person.prototype.jbo = 'teacher';
Person.prototype.sayName = function()
{ alert(this.name);};
var person1 = new Person();
var person2 = new Person();
person1.name ='Greg';alert(person1.name);

// 优化后,减少重复的Person.prototype输入
function Person(){}
Person.prototype = {
	name: 'Nike',
	age: 20,
	sayName: function() {
		console.log(this.name)
	}
}	
var person1 = new Person();

优点:创建实例时,方法不会被重新创建
缺点:
1、所有的属性和方法都共享(共享原型链)
2、不能初始化参数

7、使用构造函数和原型组合模式创建

// 创建构造函数
function Person(name, age, job) {
	this.name = name;
	this.age = age;
	this.job = job;
}
// 利用原型新增方法
Person.prototype.sayName = function() {
         console.log(this.name)
}
var person1 = new Person('zhangsan', 26, 'teacher');
person1.sayName();// 'zhangsan'

优点:该共享的共享(构造函数的调用方法共享),该私有的私有(每个实例对象参数私有),使用最广泛的方式。

@GGXXMM GGXXMM added the ⭐️ js js knowledge label Dec 6, 2021
@GGXXMM GGXXMM changed the title JavaScript创建对象的多种方式及优缺点(6种) JavaScript创建对象的多种方式及优缺点(7种) Dec 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⭐️ js js knowledge
Projects
None yet
Development

No branches or pull requests

1 participant