Home  >  Article  >  Web Front-end  >  JavaScript object-oriented programming (object creation)

JavaScript object-oriented programming (object creation)

黄舟
黄舟Original
2017-03-01 15:04:371032browse

Preface

Before learning object-oriented (object-oriented,oo) programming, you first need to know what an object is, ECMA-262, define an object as a collection of "unordered properties, whose properties can contain basic values, objects or functions". JavaScriptThere are many ways to create objects, such as: factory mode, constructor mode, prototype mode, combined constructor mode and prototype mode, parasitic constructor mode, etc.

1. Factory Pattern

The 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 classes cannot be created in ECMAScript , developers invented a function that encapsulates the details of creating objects with a specific interface.

function createStudent(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 student1= createStudent("xiaoming", 9, "student");
var student2 = createStudent("xiaowagn", 15, "student");

The function createStudent() can construct a Student object containing all necessary information based on the accepted parameters. This function can be called an unlimited number of times, and each time it returns an object containing three properties and one method. Although the factory pattern solves the problem of creating multiple similar objects, it does not solve the problem of object identification (that is, how to know the type of an object). With the development of JavaScript, another new pattern has emerged. 2. Constructor pattern

First we modify the previous code as follows:

function Student(name,age){
      this.name=name;
      this.age=age;
      this.showname=function(){
      alert(this.name);
      }
}
var xiaoming =new Student("xiaoming",6);
var xiaogang =new Student("xiaogang",7);

Difference from factory pattern:

1.

No Display the created object

2.

Assign the properties directly to

thisobject 3.

There is no

Return statement. To create an instance, use the

new

operator. Steps to create an object:

1.

Create a new object

2.

Assign the scope of the constructor Give the new object (

this points to this new object)3.

Execute the code of the constructor and add attributes to this object

4.

Return this object

 
alert(xiaoming.constructor==Student) //true;
The

constructor

attribute of the object is initially used to identify the type of an object . Check an object type, or use instanceof

alert(xiaoming instanceof Student) //true
alert(xiaoming instanceof Object) //true是因为所有对象均继承自Object

Creating a custom constructor means that instances of it can be used in the future Identified as a specific type; this is where the constructor pattern outperforms the factory pattern. There are also disadvantages to using constructors.

That is, each method must be recreated on each instance.

For example, , xiaoming and xiaogang have a showname() method. But those two methods are not instances of the same Function. ECMAScript Functions are objects, so every time a function is defined, an object is instantiated. From a logical perspective, the constructor can also be defined like this at this time.

function student(name,age){
this.name=name;
this.showName=new Function(“alert(this.name)”);
}
It can be seen that each

Student

instance contains a different Function instance. Functions with the same name on different instances are not equal. The following code demonstrates this.

alert(xiaoming.showName==xiaogang.showname);//false
2. Constructor Pattern

Every function we create has a prototype (prototype) attribute. This attribute is a pointer pointing to an object, and the purpose of this object is to contain Properties and methods that can be shared by all instances of a specific type. If understood literally, prototype is the prototype object of the object instance created by calling the constructor. The advantage of using a prototype object is that all object instances can share the properties and methods it contains. In other words, instead of defining information about an object instance in the constructor, you can add this information directly to the prototype object.

function Student(){
 
}
Student.property.name=”default name”;
Student.property.age=0;
Student.property.showName=funciton(){
alert(this.name);
}
Var xiaoming=new Student();
Var xiaogang=new Student();

与构造函数模式的不同时,新对象的这些属性和方法是由所有的实例共享的。换句话说xiaoming和xiaogang访问的都是同一组属性和同一个showName()函数。要理解原型模式的工作原理,必须先理解ECMAScript 中原型对象的性质。

1. 理解原型对象

无论什么时候,只要创建了一个新函数,就会根据一组特定的规则为该函数创建一个prototype

属性,这个属性指向函数的原型对象。在默认情况下,所有原型对象都会自动获得一个constructor

(构造函数)属性,这个属性包含一个指向prototype 属性所在函数的指针。就拿前面的例子来说,

Student.prototype. constructor 指向Student。而通过这个构造函数,我们还可继续为原型对象添加其他属性和方法.

JS中我们通过isPropertyOf()来判断,某个实例是否指向某个函数的的原型。

Eg

Student.property.isPropertyOf(xiaoming);//true。

ECMAScript5中含增加了Object.getPropertyOf()方法来获取一个实例的原型

Eg

alert(Object.getPropertyOf(xiaoming)==Student.property);//true
alert(Object.getPropertyOf(xiaoming).name);//default name

此外,我们还可以通过hasOwnProperty()方法来检测一个属性是存在实例中还是存在原型中。alert(xiaoming.hasOwnProperty(“name”));//false

alert(xiaoming.property.hasOwnProperty(“name”));//true

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

也说得过去,毕竟(如前面的例子所示),通过在实例上添加一个同名属性,可以隐藏原型中的对应属性。然而,对于包含引用类型值的属性来说,问题就比较突出.

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

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

function Student(name,age){
this.name=name;
this.age=age;
}
Student.property.showName=funciton(){alert(this.name);}

这种构造函数与原型混成的模式,是目前在ECMAScript 中使用最广泛、认同度最高的一种创建自定义类型的方法。可以说,这是用来定义引用类型的一种默认模式。

五、寄生构造函数模式

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

funciton Student(name,age){
Var o=new Object();
o.name=name;
o.age=age;
o.showName=function(){alert(this.name);}
Reurn o;
}

关于寄生构造函数模式,有一点需要说明:首先,返回的对象与构造函数或者与构造函数的原型属性之间没有关系;也就是说,构造函数返回的对象与在构造函数外部创建的对象没有什么不同。为此,不能依赖instanceof 操作符来确定对象类型。由于存在上述问题,我们建议在可以使用其他模式的情况下,不要使用这种模式。个人感觉这模式还是有点模仿工厂模式。

 以上就是JavaScript面向对象编程(对象创建)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
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