Home > Web Front-end > JS Tutorial > Follow me to learn 8 ways to create objects (classes) in JavaScript

Follow me to learn 8 ways to create objects (classes) in JavaScript

PHPz
Release: 2018-10-13 16:07:08
Original
1200 people have browsed it

8 ways to create objects (classes) in JavaScript, Yiyi introduces them to you, I hope you like them.

1. Use the Object constructor to create an object

The following code creates a person object and prints out the Name attribute value in two ways.

 var person = new Object();
  person.name="kevin";
  person.age=31;
  alert(person.name);
  alert(person["name"])
Copy after login

Another form of the above writing method is to use object literals to create an object. Don’t be surprised by person[“5”], it is legal here; otherwise use this In the bracketed way, there can be spaces between fields, such as person["my age"].

var person = 
  {
    name:"Kevin",
    age:31,
    5:"Test"
  };
  alert(person.name);
  alert(person["5"]);
Copy after login

Although the Object constructor or object literal can be used To create a single object, but these methods have an obvious shortcoming: using the same interface to create many objects will produce a lot of duplicate code. To solve this problem, people started using a variation of the factory pattern.

2. Factory pattern

Factory pattern is a well-known design pattern in the field of software engineering. This pattern abstracts the process of creating specific objects. Considering that in ECMAScript Since classes couldn't be created, developers invented functions to encapsulate the details of creating objects with a specific interface, as shown in the following example.

function createPerson(name, age, job){
  var o = new Object();
  o.name = name;
  o.age = age;
  o.job = job;
  o.sayName = function(){
    alert(this.name);
  };
  return o;
}
var person1 = createPerson("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");
Copy after login

Although the factory pattern solves the problem of creating multiple similar objects, it does not solve the problem of object recognition (that is, how to know the type of an object). With the development of JavaScript
, another new pattern has emerged.

3. Constructor pattern

Constructors like Object and Array will automatically appear in the execution environment at runtime. In addition, you can create custom constructors to define properties and methods of custom object types. For example, the previous example can be rewritten as follows using the constructor pattern.

function Person(name, age, job){
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayName = function(){
  alert(this.name);
};
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
Copy after login

In this example, the Person() function replaces the createPerson() function. We noticed that, in addition to the same parts as createPerson(), the code in Person() also has the following differences:

  • The object is not explicitly created;

  • directly assigns properties and methods to this object;

  • has no return statement.

To create a new instance of Person, the new operator must be used. Calling the constructor in this way will actually go through the following 4 steps:

(1) Create a new object;
(2) Construct The scope of the function is assigned to the new object (so this points to the new object);
(3) executes the code in the constructor (adds attributes to the new object);
(4) returns the new object.
At the end of the previous example, person1 and person2 each hold a different instance of Person. Both objects have a constructor attribute that points to Person as shown below.

alert(person1.constructor == Person); //true
alert(person2.constructor == Person); //true
Copy after login

The constructor attribute of an object is initially used to identify the object type. However, when it comes to detecting object types, the instanceof operator is more reliable. All objects we create in this example are both instances of Object and instances of Person, which can be verified through the instanceof operator.

alert(person1 instanceof Object); //true
alert(person1 instanceof Person); //true
alert(person2 instanceof Object); //true
alert(person2 instanceof Person); //true
Copy after login

Creating a custom constructor means that in the future you can identify its instances as a specific type; this is where the constructor pattern outperforms the factory pattern. . In this example, person1 and person2 are both instances of Object because all objects inherit from Object.

Problems with constructors

Although the constructor pattern is easy to use, it is not without its shortcomings. The main problem with using constructors is that each method must be recreated on each instance.

Functions in ECMAScript are objects, so every time a function is defined, an object is instantiated. From a logical perspective, the constructor at this time can also be defined like this.

function Person(name, age, job){
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayName = new Function("alert(this.name)"); // 与声明函数在逻辑上是等价的
}
Copy after login

Looking at the constructor from this perspective, it is easier to understand the essence that each Person instance contains a different Function instance (to show the name attribute). To be clear, creating a function in this way results in different scope chains and identifier resolution, but the mechanism for creating new instances of Function is still the same. Therefore, functions with the same name on different instances are not equal, as the following code can prove.

alert(person1.sayName == person2.sayName); //false
Copy after login

However, it is really not necessary to create two Function instances to complete the same task; besides, with this object, there is no need to bind the function to a specific object before executing the code. above. Therefore, you can solve this problem by moving the function definition outside the constructor as follows.

function Person(name, age, job){
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayName = sayName;
}
function sayName(){
  alert(this.name);
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
Copy after login

If the object needs to define many methods, then many global functions must be defined, so our custom reference type has no encapsulation at all. Fortunately, these problems can be solved by using the prototype pattern.

4. Prototype mode

function Person(){
}
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function(){
  alert(this.name);
};
var person1 = new Person();
person1.sayName(); //"Nicholas"
var person2 = new Person();
person2.sayName(); //"Nicholas"
alert(person1.sayName == person2.sayName); //true
Copy after login

要理解原型对象,可见我的另一篇博客:JavaScript prototype详解

前面例子中每添加一个属性和方法就要敲一遍Person.prototype。为减少不必要的输入,也为了从视觉上更好地封装原型的功能,更常见的做法是用一个包含所有属性和方法的对象字面量来重写整个原型对象,如下面的例子所示。

function Person(){
}
Person.prototype = {
  name : "Nicholas",
  age : 29,
  job: "Software Engineer",
  sayName : function () {
    alert(this.name);
  }
};
Copy after login

在上面的代码中,我们将Person.prototype 设置为等于一个以对象字面量形式创建的新对象。最终结果相同,但有一个例外:constructor 属性不再指向Person 了。前面曾经介绍过,每创建一个函数,就会同时创建它的prototype 对象,这个对象也会自动获得constructor 属性。而我们在这里使用的语法,本质上完全重写了默认的prototype 对象,因此constructor 属性也就变成了新对象的constructor 属性(指向Object 构造函数),不再指向Person 函数。此时,尽管instanceof操作符还能返回正确的结果,但通过constructor 已经无法确定对象的类型了,如下所示。

var friend = new Person();
alert(friend instanceof Object); //true
alert(friend instanceof Person); //true
alert(friend.constructor == Person); //false
alert(friend.constructor == Object); //true
Copy after login

在此,用instanceof 操作符测试Object 和Person 仍然返回true,但constructor 属性则等于Object 而不等于Person 了。如果constructor 的值真的很重要,可以像下面这样特意将它设置回适当的值。

function Person(){
}
  Person.prototype = {
  constructor : Person,
  name : "Nicholas",
  age : 29,
  job: "Software Engineer",
  sayName : function () {
    alert(this.name);
  }
};
Copy after login

需要注意一点就是:实例中的指针仅指向原型,而不指向构造函数。

原型对象的问题:原型模式也不是没有缺点。首先,它省略了为构造函数传递初始化参数这一环节,结果所有实例在默认情况下都将取得相同的属性值。虽然这会在某种程度上带来一些不方便,但还不是原型的最大问题。原型模式的最大问题是由其共享的本性所导致的。

function Person(){
}
Person.prototype = {
  constructor: Person,
  name : "Nicholas",
  age : 29,
  job : "Software Engineer",
  friends : ["Shelby", "Court"],
  sayName : function () {
    alert(this.name);
  }
};
var person1 = new Person();
var person2 = new Person();
person1.friends.push("Van");
alert(person1.friends); //"Shelby,Court,Van"
alert(person2.friends); //"Shelby,Court,Van"
alert(person1.friends === person2.friends); //true
Copy after login

5、组合使用构造函数模式和原型模式(最常用)

创建自定义类型的最常见方式,就是组合使用构造函数模式与原型模式。构造函数模式用于定义实例属性,而原型模式用于定义方法和共享的属性。结果,每个实例都会有自己的一份实例属性的副本,但同时又共享着对方法的引用,最大限度地节省了内存。另外,这种混成模式还支持向构造函数传递参数;可谓是集两种模式之长。

function Person(name, age, job){
  this.name = name;
  this.age = age;
  this.job = job;
  this.friends = ["Shelby", "Court"];
}

Person.prototype = {
  constructor : Person,
  sayName : function(){
    alert(this.name);
  }
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1.friends.push("Van");
alert(person1.friends); //"Shelby,Count,Van"
alert(person2.friends); //"Shelby,Count"
alert(person1.friends === person2.friends); //false
alert(person1.sayName === person2.sayName); //true
Copy after login

6、动态原型模式

有其他OO 语言经验的开发人员在看到独立的构造函数和原型时,很可能会感到非常困惑。动态原型模式正是致力于解决这个问题的一个方案,它把所有信息都封装在了构造函数中,而通过在构造函数中初始化原型(仅在必要的情况下),又保持了同时使用构造函数和原型的优点。换句话说,可以通过检查某个应该存在的方法是否有效,来决定是否需要初始化原型。来看一个例子。

function Person(name, age, job){
  //属性
  this.name = name;
  this.age = age;
  this.job = job;
  //方法
  ---------------------------------------------
  if (typeof this.sayName != "function"){
    Person.prototype.sayName = function(){
      alert(this.name);
    };
  }
  --------------------------------------------  
}
var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName();
Copy after login

7、寄生构造函数模式

通常,在前述的几种模式都不适用的情况下,可以使用寄生(parasitic)构造函数模式。这种模式的基本思想是创建一个函数,该函数的作用仅仅是封装创建对象的代码,然后再返回新创建的对象;但从表面上看,这个函数又很像是典型的构造函数。下面是一个例子。

function Person(name, age, job){
  var o = new Object();
  o.name = name;
  o.age = age;
  o.job = job;
  o.sayName = function(){
    alert(this.name);
  };
  return o;
}
var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName(); //"Nicholas"
Copy after login

在这个例子中,Person 函数创建了一个新对象,并以相应的属性和方法初始化该对象,然后又返回了这个对象。除了使用new 操作符并把使用的包装函数叫做构造函数之外,这个模式跟工厂模式其实是一模一样的。构造函数在不返回值的情况下,默认会返回新对象实例。

8、稳妥构造函数模式

所谓稳妥对象,指的是没有公共属性,而且其方法也不引用this 的对象。稳妥对象最适合在一些安全的环境中(这些环境中会禁止使用this 和new),或者在防止数据被其他应用程序(如Mashup程序)改动时使用。稳妥构造函数遵循与寄生构造函数类似的模式,但有两点不同:一是新创建对象的实例方法不引用this;二是不使用new 操作符调用构造函数。按照稳妥构造函数的要求,可以将前面的Person 构造函数重写如下。

function Person(name, age, job){
  //创建要返回的对象
  var o = new Object();
  //可以在这里定义私有变量和函数
  //添加方法
  o.sayName = function(){
    alert(name);
  };
//返回对象
return o;
}
Copy after login

Have you learned the above 8 methods of creating objects (classes) in JavaScript? I hope it will be helpful to your learning.

【Recommended related tutorials】

1. JavaScript video tutorial
2. JavaScript online manual
3. bootstrap tutorial

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template