Home > Web Front-end > JS Tutorial > body text

Prototype analysis in javaScript [recommended]_javascript skills

WBOY
Release: 2016-05-16 15:02:09
Original
1240 people have browsed it

I learned a lot recently when I was learning JavaScript and the prototype in js object-oriented. If there is anything wrong, I hope you can correct me.

As an object-oriented language, js naturally has the concept of inheritance, but there is no concept of classes in js, and there is no extends similar to java. Therefore, I think inheritance in js mainly relies on Prototype (chain) in js.

So, what is a prototype? We know that a function in js is also an object. When we create a function, the function actually has an attribute called prototype by default. This attribute type is called the prototype attribute. It is a pointer that points to the prototype of the function. Object, this prototype object has a default attribute called constructor, which points to the function with protptype attribute.

function Person(){}
    Person.prototype={
     // constructor:Person;
      first_name:"guo",
      hair_color:"black",
      city:"zhengzhou",
      act:function(){alert("eatting");}
    };
Copy after login

Take this as an example. We first create a function Person. This function has a default attribute prototype, pointing to the Person.propttype object. This object has a default attribute constructor (), Person.prototype.constructor-- ->Person. (In fact, the default here is to point to Object, I will correct it later)

What happens when we create an instance through the constructor?

function Person(){} 
  Person.prototype={ 
    first_name:"guo", 
    hair_color:"black", 
    city:"zhengzhou", 
    act:function(){alert("eatting");} 
  }; 
  var boy=new Person(); 
  var girl=new Person(); 
Copy after login

At this time, we need to know that the difference between constructors and functions in js is the new keyword, and a function using the new operator is a constructor. When we create an instance object of Person and save it in boy and girl, these two instance objects will generate a default attribute called _proto_ (which can be represented by [[prototype]] in ECMAScript5). This attribute points to the constructor The prototype object of the function, which is boy._proto_--->Person.prototype (has nothing to do with the constructor). At this time, boy or girl can call the attributes in the prototype object through dots. At this time, you need to know that boy and girl share the attributes of the prototype object. We can verify the above conclusion through isProtptypeOf() or object.getPrototypeOf() (the return value of this function is the prototype object, which is the value of _proto_).

alert(Person.prototype.isPrototypeOf(boy)); //true 
alert(Object.getPrototypeOf(boy).first_name);  //"guo" 
Copy after login

At this point, we can do further verification. What will happen if a property with the same name as the prototype object property is created in the instance?

var boy=new Person(); 
var girl=new Person(); 
boy.hair_color="red";  
alert(boy.hair_color);  //red 
alert(girl.hair_color); //black 
alert(Object.getPrototypeOf(boy).hair_color);  //black 
Copy after login

It can be seen that the attribute with the same name declared in the instance will block the attribute in the prototype object, but it will only overwrite it temporarily and will not affect the attribute type of the prototype object (Object.getPrototypeOf(boy).hair_color== black), it will not affect other instance objects that share the prototype object property type (girl.hair_color==black). At the same time, you can use the delete operator to delete the attributes declared by the instance object to cancel the blocking effect. We can use hasOwnProperty() to verify whether a property exists in the instance (true) or in the prototype object (false).

alert(boy.hasOwnProperty("hair_color")); //true
Copy after login

Properties can be enumerated using Object.keys().

var key=Object.keys(Person.prototype); 
alert(key); 
Copy after login

After learning this, we will find that using the above writing method to declare a prototype object will cause a problem. The constructor no longer points to Person. This is contrary to what we said that the constructor attribute of the prototype object points to the function containing the prototype attribute by default. This is because: every time a function is created, a prototype object is automatically created, and this object creates a constructor by default. Therefore, our essence here is to rewrite the default prototype, so the new consrtuctor also becomes pointing to the Object function and no longer points to the Person function. If the constructor is really important, then you need to write constructor:Person.

After that, we need to know the dynamics of the prototype. Changing the properties in the prototype object will be reflected in the instance, regardless of whether the instance is created before or after the property type of the prototype object is changed

function Person(){} 
Person.prototype={ 
  first_name:"guo", 
  hair_color:"black", 
  city:"zhengzhou", 
  act:function(){alert("eatting");} 
}; 
 
var boy=new Person(); 
Person.prototype.hobby="basketball"; 
var girl=new Person(); 
alert(boy.hobby); //basketball 
Copy after login

As can be seen from the above code, even if the modification of the prototype object properties occurs after the instance is created, the boy instance still shares Person.prototype.hobby.

However, this situation only occurs when the prototype object properties are modified. When the prototype object properties are completely rewritten, the creation of the instance must be placed after the prototype object properties are rewritten, otherwise an error will occur.

function Person(){} 
    var girl=new Person(); 
    Person.prototype={ 
      first_name:"guo", 
      hair_color:"black", 
      city:"zhengzhou", 
      act:function(){alert("eatting");} 
    }; 
 
    var boy=new Person(); 
    Person.prototype.hobby="basketball"; 
     
    alert(boy.hobby);  //basketball 
    alert(girl.first_name);  //undefined 
Copy after login

Back to the issue of "shielding", we learned earlier that creating an attribute of an instance object (with the same name as a certain attribute in the prototype object) will block the attribute of the prototype object, but will not affect other instance objects. . There is an error here. This situation only applies to basic data types. When the value of an attribute refers to a type, a big problem will occur. See the following code.

function Person(){}
    
    Person.prototype={
      first_name:"guo",
      hair_color:"black",
      friends:["Nick","John"],
      city:"zhengzhou",
      act:function(){alert("eatting");}
    };

    var boy=new Person();
    boy.friends.push("Mike");
    var girl=new Person();
    alert(boy.friends);  //Nick,John,Mike
    alert(girl.friends); //Nick,John,MIke
Copy after login

It can be seen that the above sentence does not apply. The reason is that friends exists in the prototype object, not boy, so his modification will affect this environment. (We can create attributes of a boy instance through boy.frindes=[]) Then, we need to introduce the combined use of constructor mode and prototype mode.

function Person(hair_color,city){ 
       
      this.hair_color=hair_color; 
      this.city=city; 
      this.friends=["John","Nick"]; 
    } 
    Person.prototype={ 
      constructor:Person, 
      first_name:"guo", 
      act:function() { 
         
        alert("eatting"); 
      } 
    }; 
    var boy=new Person("black","zhengzhou"); 
    var girl=new Person("red","shenyang"); 
    boy.friends.push("Nick"); 
    alert(girl.friends); 
    alert(boy.friends); 
Copy after login

此模式是目前ECMAScript中使用最廣泛,認同最高的創建自訂類型的方法,甚至可以作為一種預設模式。

但是對於從事其他物件導向語言的程式設計師來說,這樣的模式顯得很怪異,為了將所有的資訊都封裝到建構函式中,動態原型模式出現了。動態模式主要是透過一個if語句來判斷是否需要對原型物件進行初始化,以達到節省資源的目的。

此外還有穩健構造模式,是為了適應沒有共享屬性和不使用this的情況。

以上這篇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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!