Home > Article > Web Front-end > Prototype learning guide in JavaScript_Basic knowledge
What is a prototype
Function type has a property prototype, which is directly translated as prototype. This attribute is a pointer pointing to an object. This object contains some properties and methods. These properties and methods will be shared by all instances (objects) generated by the current function.
Based on what was said before, if you think about it carefully, you can get the following code:
function Person(){ ... } Person.prototype = { country : 'china', sayName : function(){ ... } }
First create an instance of Function type person, and then the method prototype of person is an object, so it is declared to point to an object. The properties and methods in this object will be shared by the instance generated by the current person function. That is to say:
person1 = new Person(); person2 = new Person();
Person1 and person2 are both regenerated instances through the Person Function type instance. They both have the same attribute country and method sayName, because they both have a pointer (__proto__) that directly points to what Person.prototype points to. object. However, please note that the __proto__ pointer is not standard. It is only defined by browsers such as Chrome and Firefox. In practice, this attribute is not used. It is only used to understand prototype:
Usage such as prototypes will be discussed in more detail later.
Mode for creating objects
Next, let’s take a look at the methods and common patterns for creating objects, as well as their advantages and disadvantages.
1. Factory mode
Just like a factory, it abstracts the process of creating specific objects and uses functions to encapsulate the details of creating objects with specific interfaces. By using functions to replace some of the duplication of work, the code is as follows:
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("jiangshui","22","engineer");
In this way, a person is created. The factory pattern solves the problem of repeated creation of multiple similar objects, but does not solve the problem of object recognition. An object is simply created, regardless of whether the object is created from a human template or an animal template, and the type of the object cannot be distinguished.
2. Constructor pattern
Create a custom constructor to define the properties and methods of the custom object type.
function Person(name, age, job){ this.name = name; this.age = age; this.job = jpb; this.sayName = function(){ alert(this.name); }; }; var person1 = new Person(...);
3. The difference between constructor pattern and factory pattern:
Person is an object of Function type. After new, an object will continue to be generated, but this newly generated object, because the parameters are passed in the function and assigned to the this pointer, then the content passed in becomes The properties or methods of the newly generated object.
The default convention for constructors is to capitalize the first letter. The execution of the above code goes through the following steps:
Instances generated in this way contain a constructor attribute pointing to the constructor by default, for example:
alert(person1.constructor == Person);
So using the constructor pattern, there is a distinction between types, and its instances can be identified as a specific type.
In addition, the constructor is an ordinary function. Because it needs feedback to obtain a new object, it is called with new. If not, the direct execution is the same as a normal function. For example, executing Person.sayName() above will pop up window.name. Because the function is executed below the window, this points to the window.
The constructor pattern is also flawed. The methods in the constructor pattern are recreated on each instance, so functions with the same name on different instances are not equal. For example:
person1.sayName == person2.sayName; //false
In other words, each object instance, property and method generated by the constructor is unique and is copied. It is necessary to make attributes unique, because this is where objects differ, but many method functions and codes are the same. Repeating them multiple times will obviously waste resources.
So we can put the function outside, and then use a pointer to point to this function in the constructor. Then in the generated instance, the method stores a pointer to a certain function, and we share the same function:
function Person(name, age){ this.name = name; this.age = age; this.sayName = sayName; } function sayName(){ alert(this.name); }
但是这样,这个函数就变成了全局函数,而且与 Person 构造函数关联性不强,没有封装性可言。
下面有请原型模式登场。
原型模式
前面已经介绍了一部分关于原型的基础知识。简单的说,就是每个函数都有一个 prototype 属性,指向一个对象(原型对象),这个对象里面可以放一些属性或者方法。然后这个函数生成的实例,会有一个不规范的属性(__proto__)指向原型。
由此来看,你应该可以理解:prototype 产生的属性和方法是所有实例共享的。
这样正好解决了上面构造函数模式中,实例中函数的共用问题。例如下面代码:
function Person(){ .... } Person.prototype.name = "jiangshui"; Person.prototype.sayName = function(){ alert(this.name); }; var person1 = new Person(); person1.sayName(); //jiangshui
或者
Person.prototype = { constructor : Person, name : "jiangshui", sayName : function(){ alert(this.name); } };
第二种方法覆盖了整个 prototype 对象,所以需要手动指定 constructor 属性,指向构造函数否则会指向 Object。
梳理一下它们的关系:
使用 isPrototypeOf() 可以确定对象之间的关系。例如:
Person.prototype.isPrototypeOf(person1);
当代码读取某个对象的某个属性,会执行搜索。先从当前对象开始,如果没有,则搜索指针指向的原型对象,而不会搜索构造函数。对象实例可以访问但是不能重写原型对象的值。如果实例中设置了与原型对象同名的属性,则搜索过程,在实例中结束而不会访问原型对象,所以达到覆盖的目的。因此即使这个属性设置为 null,也表示在实例中已经存在该属性,而不会取消掉这个属性,从而可以访问原型对应属性。
所以需要使用 delete 操作符,完全删除实例属性,从而可以重新访问原型。
原型是动态的,对原型对象所做的任何修改,都能立即从实例上反映出来。原因是实例与原型之间的松散链接关系,每次调用实例的属性方法,都会进行一次查询,如果原型变了,查询结果也就变了。
了解原型之后,我们也可以对原生对象添加新方法或属性。Object、Array、String 等原生引用类型,与上面构造函数类似,我们可以用 prototype 扩充它们的方法。例如:
String.prototype.startsWith = function(text){ return this.indexOf(text) == 0; }; var msg = "Hello World"; msg.startsWith("Hello");
这段代码为 String 这个原生引用类型,增加了一个 startsWith 方法,功能就是传递进去一个参数,看看要测试的字符串是否以参数开始。由于原型的动态性,所以只要执行一下,所有字符串类型的变量全都获得了这个方法。
但是不推荐使用这个方法,如果用的太多,代码太多,会导致维护困难、代码混乱等情况。一般情况下,会先继承某个原生引用类型,然后再在新自定义的类型上创建。关于继承,后面会再总结。
原型模式也不是万能的,原型中的所有属性和方法是被所有实例共享的,所以对于函数之类非常合适,而对于包含引用类型的属性来说,就会产生一些冲突。例如:
function Person(){} Person.prototype = { constructor : Person, friends : ["greg","jack"] }; var person1 = new Person(); var person2 = new Person(); person1.friends.push("tom"); console.log(person2.friends);
你会在 console 中看到,person2 的 friends 多了一个 tom,这并不是我想要的,但是对 person1 定义他的朋友时,的确影响到了实例 person2。
所以我们要结合原型模式和构造函数模式来使用。
组合使用构造函数模式和原型模式
这就是最常用的模式,构造函数用来定义实例属性,通过传递参数实现自定义;原型用来定义方法或者需要所有实例共享的属性。这样,既实现了自定义,又保证了共用,还避免了问题。
function Person(name, age, job){ this.name = name; this.age = age; this.job = job; this.friends = ["greg","jack"]; } Person.prototype = { constructor : Person, sayName : function(){ alert(this.name); } }; var jiangshui = new Person("jiangshui","22","engineer");
实际应用示例
OK,到了这里,你可能会看懂原型是啥,以及如何创建对象,可是,这些又有什么用?确实,我之前的工作,一直也就是用 jQuery 写一些代码就可以了,根本用不到封装然后生成对象实现功能等。那这些究竟有什么用?
这种开发方式主要用于模块化和组建化的开发。比如你常用的弹窗功能,你当然可以把弹窗有关代码,每次都粘贴复制,然后修改一下就可以用在项目里面了。更好的选择是把你的弹窗功能代码,抽象封装成这样的一个组件,这样当你需要用弹窗的时候,只需要传递参数生成一个弹窗实例,就可以调用了。
原型对象和原型链
在Javascript中,万物皆对象,但对象也有区别,大致可以分为两类,即:普通对象(Object)和函数对象(Function)。
一般而言,通过new Function产生的对象是函数对象,其他对象都是普通对象。
举例说明:
function f1(){ //todo } var f2 = function(){ //todo }; var f3 = new Function('x','console.log(x)'); var o1 = {}; var o2 = new Object(); var o3 = new f1(); console.log( typeof f1,//function typeof f2,//function typeof f3,//function typeof o1,//object typeof o2,//object typeof o3 //object ); >> function function function object object object
f1属于函数的声明,最常见的函数定义方式,f2实际上是一个匿名函数,把这个匿名函数赋值给了f2,属于函数表达式,f3不常见,但也是一种函数对象。
Function是JS自带的对象,f1,f2在创建的时候,JS会自动通过new Function()的方式来构建这些对象,因此,这三个对象都是通过new Function()创建的。
在Javascript中创建对象有两种方式:对象字面量和使用new表达式,o1和o2的创建恰好对应了这两种方式,重点讲一下o3, 如果用Java和C#的思路来理解的话,o3是f1的实例对象,o3和f1是同一类型,至少我以前这么认为,其实不然…
那么怎么理解呢? 很简单,看o3是不是通过new Function产生的, 显然不是,既然不是函数对象,那就是普通对象 。
通过对函数对象和普通对象的简单理解之后,我们再来了解一下Javascript中的原型和原型链:
在JS中,每当创建一个函数对象f1 时,该对象中都会内置一些属性,其中包括prototype和__proto__, prototype即原型对象,它记录着f1的一些属性和方法。
需要注意的是,prototype 对f1是不可见的,也就是说,f1不会查找prototype中的属性和方法。
function f(){} f.prototype.foo = "abc"; console.log(f.foo); //undefined
那么,prototype有什么用呢? 其实prototype的主要作用就是继承。 通俗一点讲,prototype中定义的属性和方法都是留给自己的“后代”用的,因此,子类完全可以访问prototype中的属性和方法。
想要知道f1是如何把prototype留给“后代”,我们需要了解一下JS中的原型链,此时,JS中的 __proto__ 入场了,这哥们长的很奇特,隐藏的也很深,以致于你经常见不到它,但它在普通对象和函数对象中都存在, 它的作用就是保存父类的prototype对象,JS在通过new 表达式创建一个对象的时候,通常会把父类的prototype赋值给新对象的__proto__属性,这样,就形成了一代代传承…
function f(){} f.prototype.foo = "abc"; var obj = new f(); console.log(obj.foo); //abc
现在我们知道,obj中__proto__保存的是f的prototype, 那么f的prototype中的__proto__中保存的是什么呢? 看下图:
如图所示,f.prototype的__proto__中保存的是Object.prototype,Object.prototype对象中也有__proto__,而从输出结果看,Object.prototype.__proto__ 是null,表示obj对象原型链的终结。如下图所示:
obj对象拥有这样一个原型链以后,当obj.foo执行时,obj会先查找自身是否有该属性,但不会查找自己的prototype,当找不到foo时,obj就沿着原型链依次去查找…
在上面的例子中,我们在f的prototype上定义了foo属性,这时obj就会在原型链上找到这个属性并执行。