understanding of the prototype js

Reprinted: https://www.cnblogs.com/douyage/p/8630529.html

In a typical object-oriented language, as java, there is the concept of class (class) of the object instance of the class is a template that is the object class. However, in Javascript language systems, the concept of class (Class) does not exist, javascript is not based on the 'class', but by the constructor (constructor) and chain prototype (prototype chains) implementation. But ES6 provided in a language closer to the traditional wording, the introduction of the Class (class) concept as a template object. By class keyword, you can define classes. Basically, ES6 the class can be seen as just a syntactic sugar, most of its functions, ES5 can do, just let the wording of the new class prototype object more clearly written, like object-oriented programming syntax only.

  According to my habit, before writing the article I will give the article directories.

  The following content will be divided into the following sections:

  1. brief constructor

  2. disadvantage constructor

  The role of 3.prototype property

  4. Chain prototype (prototype chain)

  5.constructor property

    5.1: The role of the constructor property

  Operators 6.instanceof

1. brief constructor

  Close relationship in my article a Javascript in the constructor and new orders in detail introduces the concept and characteristics of the constructor, principles and usage of the new command, if the constructor for the students are not familiar with, you can go thin taste. The following do a simple review.

  The so-called constructor function is to provide a basic configuration of a template object is generated and description of the object. A constructor may generate a plurality of objects, each object has the same structure. Overall, the constructor is a template object, the object is an instance constructor.

  Features constructors are:

    a: the first letter of the constructor function name must be capitalized.

    b: internal use this object to point to the object instance to be generated.

    c: use the new operator to call the constructor, and returns the object instance.

  A look at a simple example.

1
2
3
4
5
function  Person(){
  this .name =  'keith' ;
}
  var  boy =  new  Person();
console.log(boy.name);  //'keith'

2. disadvantage constructor

  All instances of objects can inherit attributes and methods constructor. However, between the same object instance, can not be shared properties.

1
2
3
4
5
6
7
8
9
10
11
12
function  Person(name,height){
  this .name=name;
  this .height=height;
  this .hobby= function (){
  return  'watching movies' ;
}
  }
var  boy= new  Person( 'keith' ,180);
  var  girl= new  Person( 'rascal' ,153);
  console.log(boy.name);  //'keith'
  console.log(girl.name);  //'rascal'
  console.log(boy.hobby===girl.hobby);  //false

 The above code, a constructor Person object instances generated two boy and girl, and has two properties and a method. However, their hobby is not the same method. In other words, every time you use the new constructor to call back in an object instance, that they will create a hobby method. This is not only unnecessary, but also a waste of resources, because all methods are hobby faces of the children's behavior, it can be two shared object instance.

  Therefore, a disadvantage is that the constructor: between object instance with a constructor property or method can not be shared.

The role of 3.prototype property

  In order to address the shortcomings can not be shared between the properties of the object instance constructor, js provide a prototype property.

  js each data type is an object (except null and undefined), and each object inherits from another object, the latter is called the "prototype" (the prototype) objects, with the exception of null, it does not have its own prototype object.

  All methods and properties of the prototype object, will be shared object instance.

  By generating object instance constructor prototype will point to the object instance constructor prototype property. Each constructor has a prototype property, this property is the prototype object object instance.

1
2
3
4
5
6
7
8
9
10
11
12
function  Person(name,height){
this .name=name;
this .height=height;
}
Person.prototype.hobby= function (){
return  'watching movies' ;
}
var  boy= new  Person( 'keith' ,180);
var  girl= new  Person( 'rascal' ,153);
console.log(boy.name);  //'keith'
console.log(girl.name);  //'rascal'
console.log(boy.hobby===girl.hobby);  //true

  In the above code, if the method of the hobby on the prototype object, then the two objects are instances share the same method. I hope you can understand that, for the constructor who, prototype as a constructor property; for with object instances, prototype is a prototype object object instance. So that is the prototype property, but also the object.

  Properties of the prototype object attribute is not an object instance. Property is inherited from object instance constructor defined attributes, functions as an internal structure of a key to point to this instance of the object to be generated. Properties of the object instance is actually inside the constructor defined attributes. Just modify the properties and methods on the prototype object, change will be immediately reflected in all object instances.

 

  In the above code, after modifying the prototype object hobby method, two object instances have changed. This is because the object instance is actually no method hobby, hobby is reading method prototype object. That is, when an object instance does not have the properties and methods, will look up to the prototype object. If an instance of the object itself has a property or method, you will not find on the prototype object.

1
2
3
4
5
boy.hobby= function (){
  return  'play basketball' ;
  }
  console.log(boy.hobby());  //'play basketball'
  console.log(girl.hobby());  //'swimming'

  In the above code, object instances when hobby boy method changes, the method would not inherit hobby on a prototype object. But the girl still inherit the prototype object.

  in conclusion:

  a: the role of the prototype object, is to define the attributes and methods of the shared object instances.

  b: prototype, for the constructor, it is an attribute; for the object instance, it is a prototype object.

4. Chain prototype (prototype chains)

  Properties and methods of an object, there may be defined in its own, there may be defined in its prototype object. Since the prototype object itself is also an object instance of the object, it has its prototype, the prototype is formed of a chain (prototype chain). For example, the object A is the prototype object b, b c objects prototype object, and so on. All prototypes top all objects are Object.prototype, that object that is the prototype property Object constructor points.

  Of course, Object.prototype the object has its own prototype object, any object that is not null attributes and methods, and the null object does not have its own prototype.

1 console.log(Object.getPrototypeOf(Object.prototype)); //null

2 console.log(Person.prototype.isPrototypeOf(boy)) //true

  Prototype chain (prototype chain) features are:

    a: When reading an attribute of an object, JavaScript engine to find the properties of the object itself, if not, go on to its prototype, if this fails, go on to the prototype of the prototype. If until the topmost Object.prototype still not found, returns undefined.

    b: If the object itself and its prototype, defines a property of the same name, then the priority read object's own properties, this is called "covering" (overiding).

    c: one level up in the prototype chain looking for a property, the performance is influential. Looking for property in the upper layer of the prototype object, the greater the impact on performance. If looking for a property that does not exist, it will traverse the entire prototype chain.

  Look concept may be more obscure, we look at an example. It is really important to understand the concept.

 

   The above code, a set of array ARR, there are three array elements. We do not have to add any array properties and methods, but they call in length, when the join (), valueOf (), but does not complain.

  The length property is inherited from Array.prototype, belonging to a property on the prototype object. join method is inherited from Array.prototype, belonging to a method on the prototype object. These two methods are shared by all arrays. When there is no length property on this instance of an object, the object will be to find the prototype.

  valueOf method is inherited from the Object.prototype. First, arr array is not valueOf method, so we look to the prototype object Array.prototype. Then, Array.prototype found no valueOf method on the object. Finally, to Object.prototype find its prototype object.

  Take a look at Array.prototype Object.prototype objects and objects are what properties and methods.

1
2
3
4
console.log(Object.getOwnPropertyNames(Array.prototype))
//["length", "toSource", "toString", "toLocaleString", "join", "reverse", "sort", "push", "pop", "shift", "unshift", "splice", "concat", "slice", "lastIndexOf", "indexOf", "forEach", "map", "filter", "reduce", "reduceRight", "some", "every", "find", "findIndex", "copyWithin", "fill", "entries", "keys", "values", "includes", "constructor", "$set", "$remove"]
  console.log(Object.getOwnPropertyNames(Object.prototype))
  // ["toSource", "toString", "toLocaleString", "valueOf", "watch", "unwatch", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__", "__proto__", "constructor"]

  I believe that we see here, for prototype or half-comprehended. This is normal, after all, is more important js and relatively abstract concept, not be so quick to master, then eating more than a few, maybe grasp its essence. At some peace, there is a living example of the problem, and perhaps you will encounter. Js can look at the constructor and prototype objects.

5.constructor property

  prototype object has a constructor property, pointing to default constructor prototype object is located.

 

  Note that, prototype is a property of the constructor, and the constructor prototype property is an object that points to the constructor, which is the property of the prototype object. Be careful not to confuse.

 

  Since the constructor property is defined in the prototype (prototype) objects above, it means that all instances of an object can be inherited.

1
2
3
4
function  A(){};
  var  a= new  A();
  console.log(a.constructor);  //A()
console.log(a.constructor===A.prototype.constructor); //true

  The above code, a is an instance of the object constructor A, but itself is not a contructor property, which actually read the above prototype chain

A.prototype.constructor属性。

  5.1: The role of the constructor property

   a: resolving prototype object constructor function which belongs in the end

1
2
3
4
function  A(){};
var  a= new  A();
console.log(a.constructor===A)  //true
console.log(a.constructor===Array)  //false

    上面代码表示,使用constructor属性,确定实例对象a的构造函数是A,而不是Array。

    b:从实例新建另一个实例

1
2
3
4
function  A() {};
  var  a =  new  A();
var  b =  new  a.constructor();
console.log(b  instanceof  A);  //true

    上面代码中,a是构造函数A的实例对象,可以从a.constructor间接调用构造函数。

    c:调用自身的构造函数成为可能

1
2
3
A.prototype.hello =  function () {
return  new  this .constructor();
}

    d:提供了一种从构造函数继承另外一种构造函数的模式

1
2
3
4
5
function  Father() {}
  function  Son() {
Son.height.constructor.call( this );
  }
  Son.height =  new  Father();

    上面代码中,Father和Son都是构造函数,在Son内部的this上调用Father,就会形成Son继承Father的效果。

    e:由于constructor属性是一种原型对象和构造函数的关系,所以在修改原型对象的时候,一定要注意constructor的指向问题。

    解决方法有两种,要么将constructor属性指向原来的构造函数,要么只在原型对象上添加属性和方法,避免instanceof失真。

6.instanceof运算符

  instanceof运算符返回一个布尔值,表示指定对象是否为某个构造函数的实例。

 

  因为instanceof对整个原型链上的对象都有效,所以同一个实例对象,可能会对多个构造函数都返回true。

 

 注意,instanceof对象只能用于复杂数据类型(数组,对象等),不能用于简单数据类型(布尔值,数字,字符串等)。

 

  此外,null和undefined都不是对象,所以instanceof 总是返回false。

 

  利用instanceof运算符,还可以巧妙地解决,调用构造函数时,忘了加new命令的问题。

 

  上面代码中,使用了instanceof运算符来判断函数体内的this关键字是否指向构造函数Keith的实例,如果不是,就表明忘记加new命令,此时构造函数会返回一个对象实例,避免出现意想不到的结果。

  因为限于篇幅的原因,暂时介绍到这里。

  我会在下次的分享中谈谈原型(prototype)对象的一些原生方法,如Object.getPrototypeOf(),Object.setPrototypeOf()等,并且介绍获取原生对象方法的比较。

以上所述是小编给大家介绍的详解Javascript中prototype属性(推荐)的相关知识,希望对大家有所帮助

Guess you like

Origin www.cnblogs.com/itgezhu/p/11263676.html