louzhedong / blog

前端基础,深入以及算法数据结构

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JS中的创建对象

louzhedong opened this issue · comments

Javascript的创建对象和传统的OO语言不一样,有一些特别的地方需要我们去注意。文章作为阅读红皮书(JS高程)的笔记,记录Javascript语言中的创建方式。

工厂模式
function createPerson(name, age, job) {
  const o = new Object();
  o.name = name;
  o.age = age;
  o.job = job;
  o.sayName = function() {
    alert(this.name);
  };
  return o;
}

const person = createPerson('michael', 22, 'student');

可以通过工厂模式创建无数个对象,并且这无数个对象互不相干,但通过工厂模式创建的对象无法知道其类型

构造函数模式
function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayName = function() {
    alert(this.name);
  };
}

const person = new Person('michael', 22, 'student');

通过构造函数模式创建的对象,可以知道其类型,通过下列的方式

person.constructor === Person;
person instanceof Person;

构造函数模式的问题:

每个方法都要在每个实例上重新创建一遍

原型模式

我们创建的每个函数都有一个prototype(原型)属性,这个属性是一个指针,指向一个对象,而这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法

function Person() {
}
Person.prototype.name = 'michael';
Person.prototype.age = 22;
Person.prototype.job = 'student';
Person.prototype.sayName = function() {
  alert(this.name);
};

此时创建出的对象的属性和方法是由所有实例共享的

另一种原型模式的表示方法

function Person() {
}
Person.prototype = {
  constructor: Person,
  name: 'michael',
	age: 22,
	job: 'student',
	sayName: function() {
  	alert(this.name);
	};
}

原型模式的问题就是所有实例会共享属性

组合使用构造函数模式和原型模式

构造函数模式用于定义实例属性,原型模式用于定义方法和共享属性

function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
}

Person.prototype = {
  constructor: Person,
	sayName: function() {
  	alert(this.name);
	};
}

const person = createPerson('michael', 22, 'student');
动态原型模式

动态原型模式将所有信息都封装在构造函数中

function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
  Person.prototype.sayName = function() {
  	alert(this.name);
	};
}

const pserson = createPerson('michael', 22, 'student');
寄生构造函数模式
function Person(name, age, job) {
	const o = new Object();
  o.name = name;
  o.age = age;
  o.job = job;
  o.sayName = function() {
    alert(this.name);
  };
  return o;
}

const person = new Person('michael', 22, 'student');

除了使用new操作符,这个模式和工厂模式一模一样

稳妥构造函数模式

稳妥构造函数中不使用this和new,适用于安全环境中

function Person(name, age, job) {
  const o = new Object();
  o.sayName = function() {
    alert(name);
  };
  return o;
}

const person = Person('michael', 22, 'student');

在这个例子中,除了调用sayName方法,没有其他方式访问其数据成员