Home > Web Front-end > JS Tutorial > A brief analysis of various modes of creating objects in javascript_javascript skills

A brief analysis of various modes of creating objects in javascript_javascript skills

WBOY
Release: 2016-05-16 15:01:50
Original
1392 people have browsed it

I am currently reading "Advanced Programming with JavaScript" (Second Edition)

Creation of objects in javascript

•Factory Mode

•Constructor Pattern

•Prototype Mode

• Combine constructor and prototype patterns

•Prototype dynamic mode

Most object-oriented languages ​​have the concept of a class, through which multiple objects with the same methods and properties can be created. Although technically speaking, JavaScript is an object-oriented language, JavaScript does not have the concept of classes, everything is an object. Any object is an instance of a certain reference type, which is created through an existing reference type; the reference type can be native or customized. Native reference types include: Object, Array, Data, RegExp, and Function. ! A reference type is a data structure that organizes data and functionality, often called a class. In JavaScript, which lacks the concept of classes, the problem that needs to be solved is how to create objects efficiently.

1.1.0. General methods of creating objects

var person = {}; //对象字面量表示,等同于var person = new Objcect();

person.name = 'evansdiy';
person.age = '22';
person.friends = ['ajiao','tiantian','pangzi'];
person.logName = function() {
  console.log(this.name);
}
Copy after login

Based on the Object reference type, an object is created, which contains four properties, one of which is a method. If you need many instances of person-like objects, there will be a lot of duplicate code.

1.1.1. Factory mode [top]

Create an object through a function that can contain object details, and then return this object.

function person(name,age,friends) {

  var o = {
    name: name,
    age: age,
    friends: friends,
    logName: function() {
      console.log(this.name);
    }
  };

  return o;

}

var person1 = person('Evansdiy','22',['ajiao','tiantian','pangzi']);
Copy after login

Every time the person function is called, a new object will be created through the object o inside the function, and then returned. Apart from this, the internal object o that exists to create a new object has no other purpose. In addition, it is impossible to determine the type of object created by the factory pattern.

1.1.2. Constructor pattern [top]

function Person(name,age,job) {

  this.name = name;
  this.age = age;
  this.job = job;
  this.logName = function() {
    console.log(this.name);
  }

}

//通过new操作符创建Person的实例
var person1 = new Person('boy-a','22','worker');

var person2 = new Person('girl-b','23','teacher');

person1.logName(); //boy-a

person2.logName(); //girl-a
Copy after login

Comparing the factory pattern, you can find that there is no need to create intermediate objects here and there is no return. In addition, the instance of the constructor can be identified as a specific type, which solves the problem of object identification (by checking the constructor property of the instance, or using the instanceof operator to check whether the instance was created through a certain constructor).

console.log(person1.constructor == Person);//constructor is located in the constructor prototype and points to the constructor, and the result is true

console.log(person1 instanceof Person);//Use the instanceof operator to determine whether person1 is an instance of the constructor Person. However, the constructor mode also has its own problems. In fact, the logName method will be restarted on each instance. Create once. It should be noted that the methods created by instantiation are not equal. The following code will get false:

console.log(person1.logName == person2.logName);//falseWe can solve this problem by moving the method outside the constructor (becoming a global function):

function logName() {
  console.log(this.name);
}

function logAge() {
  console.log(this.age);
}
Copy after login

However, the global function created under the global function can actually only be called by the instance created by Person, which is a bit unworthy of its name; if there are many methods, they need to be defined one by one, lacking encapsulation.

1.1.3. Prototype mode [top]

Every function in JavaScript contains a pointer to the prototype attribute (most browsers can access it through the internal attribute __proto__). The prototype attribute is an object that contains all instances created by a certain reference type. Shared properties and methods.

function Person() {}

Person.name = 'evansdiy';

Person.prototype.friends = ['ajiao','jianjian','pangzi'];

Person.prototype.logName = function() {
  console.log(this.name);
}

var person1 = new Person();

person1.logName();//'evansdiy'
Copy after login

The above code does the following things:

1. A constructor function Person is defined, and the Person function automatically obtains a prototype attribute, which by default only contains a constructor attribute pointing to Person;

2. Add three attributes through Person.prototype, one of which is a method;

3. Create an instance of Person and then call the logName() method on the instance.

What needs to be noted here is the calling process of the logName() method:

1. Look for the logName() method on the person1 instance and find that there is no such method, so we trace it back to the prototype of person1

2. Find the logame() method on the prototype of person1. There is this method, so calling this method is based on such a search process. We can prevent the instance from accessing the prototype by defining the same-name attribute in the prototype on the instance. Attributes with the same name. It should be noted that doing so will not delete the attributes with the same name on the prototype, but only prevent instance access.

var person2 = new Person();

person2.name = 'laocai'; If we no longer need the attributes on the instance, we can delete them through the delete operator.

delete person2.name; Use a for-in loop to enumerate all properties that the instance can access (whether the property exists in the instance or the prototype):

for(i in person1) {
  console.log(i);
}
Copy after login

同时,也可以利用hasOwnProperty()方法判断某个属性到底存在于实例上,还是存在于原型中,只有当属性存在于实例中,才会返回true:

console.log(person1.hasOwnProperty('name'));//true!hasOwnProperty来自Object的原型,是javascript中唯一一个在处理属性时不查找原型链的方法。[via javascript秘密花园] 另外,也可以通过同时使用in操作符和hasOwnProperty()方法来判断某个属性存在于实例中还是存在于原型中:

console.log(('friends' in person1) && !person1.hasOwnProperty('friends'));先判断person1是否可以访问到friends属性,如果可以,再判断这个属性是否存在于实例当中(注意前面的!),如果不存在于实例中,就说明这个属性存在于原型中。 前面提到,原型也是对象,所以我们可以用对象字面量表示法书写原型,之前为原型添加代码的写法可以修改为:

Person.prototype = {

  name: 'evansdiy',
  friends: ['ajiao','jianjian','pangzi'],
  logName: function() {
    console.log(this.name);
  }

}
Copy after login

由于对象字面量语法重写了整个prototype原型,原先创建构造函数时默认取得的constructor属性会指向Object构造函数:

//对象字面量重写原型之后

console.log(person1.constructor);//Object不过,instanceof操作符仍会返回希望的结果:

//对象字面量重写原型之后

console.log(person1 instanceof Person);//true当然,可以在原型中手动设置constructor的值来解决这个问题。

Person.prototype = {

  constructor: Person,
  ......

}
Copy after login

如果在创建对象实例之后修改原型对象,那么对原型的修改会立即在所有对象实例中反映出来:

function Person() {};

var person1 = new Person();

Person.prototype.name = 'evansdiy';

console.log(person1.name);//'evansdiy'
Copy after login

实例和原型之间的连接仅仅是一个指针,而不是一个原型的拷贝,在原型实际上是一次搜索过程,对原型对象的所做的任何修改都会在所有对象实例中反映出来,就算在创建实例之后修改原型,也是如此。 如果在创建对象实例之后重写原型对象,情况又会如何?

function Person() {};

var person1 = new Person1();//创建的实例引用的是最初的原型

//重写了原型
Person.prototype = {
  friends: ['ajiao','jianjian','pangzi']
}

var person2 = new Person();//这个实例引用新的原型

console.log(person2.friends);

console.log(person1.friends);
Copy after login

以上代码在执行到最后一行时会出现未定义错误,如果我们用for-in循环枚举person1中的可访问属性时,会发现,里头空无一物,但是person2却可以访问到原型上的friends属性。 !重写原型切断了现有原型与之前创建的所有对象实例的联系,之前创建的对象实例的原型还在,只不过是旧的。

//创建person1时,原型对象还未被重写,因此,原型对象中的constructor还是默认的Person()

console.log(person1.constructor);//Person()

//但是person2的constructor指向Object()

console.log(person2.constructor);//Object()需要注意的是,原型模式忽略了为构造函数传递参数的过程,所有的实例都取得相同的属性值。同时,原型模式还存在着一个很大的问题,就是原型对象中的引用类型值会被所有实例共享,对引用类型值的修改,也会反映到所有对象实例当中。

function Person() {};

Person.prototype = {
  friends: ['ajiao','tiantian','pangzi']
}

var person1 = new Person();

var person2 = new Person();

person1.friends.push('laocai');

console.log(person2.friends);//['ajiao','tiantian','pangzi','laocai']
Copy after login

修改person1的引用类型值friends,意味着person2中的friends也会发生变化,实际上,原型中保存的friends实际上只是一个指向堆中friends值的指针(这个指针的长度是固定的,保存在栈中),实例通过原型访问引用类型值时,也是按指针访问,而不是访问各自实例上的副本(这样的副本并不存在)。

1.1.4.结合构造函数和原型模式创建对象 [top]

结合构造函数和原型模式的优点,弥补各自的不足,利用构造函数传递初始化参数,在其中定义实例属性,利用原型定义公用方法和公共属性,该模式应用最为广泛。

function Person(name,age) {

  this.name = name;
  this.age = age;
  this.friends = ['ajiao','jianjian','pangzi'];

}

Person.prototype = {

  constructor: Person,
  logName: function() {
    console.log(this.name);
  }

}

var person1 = new Person('evansdiy','22');

var person2 = new Person('amy','21');

person1.logName();//'evansdiy'

person1.friends.push('haixao');

console.log(person2.friends.length);//3
Copy after login

1.1.5.原型动态模式 [top]

原型动态模式将需要的所有信息都封装到构造函数中,通过if语句判断原型中的某个属性是否存在,若不存在(在第一次调用这个构造函数的时候),执行if语句内部的原型初始化代码。

function Person(name,age) {

  this.name = name;
  this.age = age;

  if(typeof this.logName != 'function') {
    Person.prototype.logName = function() {
      console.log(this.name);
    };
    Person.prototype.logAge = function() {
      console.log(this.age);
    };
  };

}

var person1 = new Person('evansdiy','22');//初次调用构造函数,此时修改了原型

var person2 = new Person('amy','21');//此时logName()方法已经存在,不会再修改原型
Copy after login

需要注意的是,该模式不能使用对象字面量语法书写原型对象(这样会重写原型对象)。若重写原型,那么通过构造函数创建的第一实例可以访问的原型对象不会包含if语句中的原型对象属性。

function Person(name,age) {

  this.name = name;
  this.age = age;

  if(typeof this.logName != 'function') {
    Person.prototype = {
      logName: function() {
        console.log(this.name);
      },
      logAge: function() {
        console.log(this.Age);
      }
    }
  };

}

var person1 = new Person('evansdiy','22');

var person2 = new Person('amy','21');

person2.logName();//'amy'

person1.logName();//logName()方法不存在
Copy after login

需要说明的是,各模式都有自己的应用场景,无所谓优劣。

以上这篇浅析在javascript中创建对象的各种模式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

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