Below I will bring you an analysis of various patterns for creating objects in JavaScript. Now share it with everyone, and also give everyone a reference
Creation of objects in javascript
•Factory pattern
•Constructor pattern
•Prototype pattern
•Combining constructor and prototype patterns
•Prototype dynamic pattern
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 method of creating an object
var person = {}; //对象字面量表示,等同于var person = new Objcect(); person.name = 'evansdiy'; person.age = '22'; person.friends = ['ajiao','tiantian','pangzi']; person.logName = function() { console.log(this.name); }
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 pattern
Create an object through a function that can contain the details of the object, and then return the 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']);
Every time the person function is called, a new object will be created through the object o inside the function, and then returned. In addition, this 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
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
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 recreated on each instance. It should be noted that, it is created by instantiation. methods are not equal, the following code will get false:
console.log(person1.logName == person2.logName);//false we can move the method outside the constructor (become global function) to solve this problem:
function logName() { console.log(this.name); } function logAge() { console.log(this.age); }
However, the global function created under the global context 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, Lack of encapsulation.
1.1.3. Prototype mode
Every function in JavaScript contains a pointer to the prototype attribute (most browsers can use the internal attribute __proto__ access), the prototype property is an object that contains properties and methods shared by all instances created by a certain reference type.
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'
The above code does the following things:
1. Defines a constructor function Person. The Person function automatically obtains a prototype attribute, which by default only contains a constructor attribute pointing to Person. ;
2. Add three properties 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. Search the logName() method on the person1 instance and find that there is no such method, so 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 on the prototype. It should be noted that doing so will not delete the attributes with the same name on the prototype, but only prevents 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); }
At the same time, you can also Use the hasOwnProperty() method to determine whether a property exists on the instance or in the prototype. Only when the property exists in the instance will it return 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); } }
由于对象字面量语法重写了整个prototype原型,原先创建构造函数时默认取得的constructor属性会指向Object构造函数:
//对象字面量重写原型之后
console.log(person1.constructor);//Object不过,instanceof操作符仍会返回希望的结果:
//对象字面量重写原型之后
console.log(person1 instanceof Person);//true当然,可以在原型中手动设置constructor的值来解决这个问题。
Person.prototype = { constructor: Person, ...... }
如果在创建对象实例之后修改原型对象,那么对原型的修改会立即在所有对象实例中反映出来:
function Person() {}; var person1 = new Person(); Person.prototype.name = 'evansdiy'; console.log(person1.name);//'evansdiy'
实例和原型之间的连接仅仅是一个指针,而不是一个原型的拷贝,在原型实际上是一次搜索过程,对原型对象的所做的任何修改都会在所有对象实例中反映出来,就算在创建实例之后修改原型,也是如此。 如果在创建对象实例之后重写原型对象,情况又会如何?
function Person() {}; var person1 = new Person1();//创建的实例引用的是最初的原型 //重写了原型 Person.prototype = { friends: ['ajiao','jianjian','pangzi'] } var person2 = new Person();//这个实例引用新的原型 console.log(person2.friends); console.log(person1.friends);
以上代码在执行到最后一行时会出现未定义错误,如果我们用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']
修改person1的引用类型值friends,意味着person2中的friends也会发生变化,实际上,原型中保存的friends实际上只是一个指向堆中friends值的指针(这个指针的长度是固定的,保存在栈中),实例通过原型访问引用类型值时,也是按指针访问,而不是访问各自实例上的副本(这样的副本并不存在)。
1.1.4.结合构造函数和原型模式创建对象
结合构造函数和原型模式的优点,弥补各自的不足,利用构造函数传递初始化参数,在其中定义实例属性,利用原型定义公用方法和公共属性,该模式应用最为广泛。
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
1.1.5.原型动态模式
原型动态模式将需要的所有信息都封装到构造函数中,通过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()方法已经存在,不会再修改原型
需要注意的是,该模式不能使用对象字面量语法书写原型对象(这样会重写原型对象)。若重写原型,那么通过构造函数创建的第一实例可以访问的原型对象不会包含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()方法不存在
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
详细解读JavaScript设计模式开发中的桥接模式(高级篇)
详细解读在JavaScript中实现设计模式中的适配器模式的方法(图文教程)
设计模式中的facade外观模式在JavaScript开发中的运用(高级篇)
The above is the detailed content of Analysis of various modes of creating objects in javascript (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!