Prototype prototype

js Object comparison of

because js Is the language of interpretation and execution , Then the function and object appear in the code. If they are executed repeatedly , Multiple copies are created

  1. Code that is repeatedly executed in code is prone to duplicate objects
  2. Create a Person Constructors , In order to create object . Ask for name, age, gender and sayHello
  3. Errors in the code
 // 1
function Person() {
var o = {};
o.name = ...
return o;
}
// 2
function Person () {
name: ....
age: ....
...
}
  1. The way traditional construction methods are defined affects performance , It is easy to cause multiple objects to have multiple method copies . It should be said that the methods are extracted separately . Let all objects share this method .
  2. We can consider putting all the methods out, but there are security risks
    • Various frameworks or libraries will be introduced into the development . The more members you customize , The more likely there is a naming conflict
    • There may be multiple constructors in development . Each constructor should have more than one method . It's not easy to maintain .
  3. Any object will be linked to its prototype by default
    • Create a function . A special object will be created . This object uses function .prototype quote . Call it the prototype property of a function .
    • Every object created by this function as a constructor , Will be connected to the object by default .
    • When the object accesses a method or property , If there is no , I'll go to this mysterious object to find .

The problem with traditional constructors

 function Foo() {
this.sayHello = function () {
}
}
  1. Because the object is a call new Foo() Created by . So when every object is created , function sayHello Will be created once
  2. So each object has an independent , Different , But functions with the same functional logic . such as : {} == {}
  3. In code, methods consume performance . The most typical resource is memory .
  4. The best way to do this is to put the function body outside the constructor . Then you just need to refer to the function in the constructor
 function sayHello () {}
function Foo () {
this.say = sayHello;
}
  1. It's going to be difficult in development : Introducing frame hazards , The code is too cumbersome to maintain . The solution is if the outside function doesn't take up the name . And it's better to be under the function .
  2. When every function is defined , A mysterious object was created .
  3. Every object created by the constructor will be connected to the mysterious object by default .
 var f1 = new Foo();
var f2 = new Foo();
f1.sayHello(); // If f1 No, sayHello, Then it will be in Foo.prototype Middle search
f2.sayGoodBye(); // If f2 There is no change in the method , Then it will be in Foo.prototype Middle search
  1. Many objects created by constructors share one object , Namely Constructors .prototype
  2. Just put what you share , Repeat things that take up more memory Constructors .prototype in , Then all objects can be shared .
 function Foo() {}
Foo.prototype.sayHello = function () {
console.log( ... );
};
var f1 = new Foo();
f1.sayHello();
var f2 = new Foo();
f2.sayHello(); f1.sayHello === f2.sayHello
  1. practice : Write a constructor Student, Ask for name, age, gender, sayHello, study. Require constructor with parameters .

Common mistakes

  1. Write Constructors .prototype When , Add attributes to it as well .
 function Person() {}
Person.prototype.name = ' Zhang San ';
var p = new Person();
  1. Error in assignment
 function Person() {}
Person.prototype.name = ' Zhang San ';
var p1 = new Person();
var p2 = new Person();
p1.name = ' Li Si '; console.log( p1.name );
console.log( p2.name );
// If it's data access , If there is no such data in the current object, go to the prototype property of the constructor
// If it's writing data , When there is this data in the object , That's the modified value ; If the object does not have that data , Then add value

Prototype related concepts

  1. About the concept of object orientation

    • class class: stay js In this case, it's the constructor

      • In traditional object-oriented languages , Use something called a class to define the template . Then use the template to create the object .
      • It has a similar function in the construction method . So it's called a class
 // stay java in , The smallest code unit is class 
class Program {
// member
}
* example ( instance ) With the object ( object )
* Instance generally refers to the object created by a constructor . We become xxx Instance of constructor
* Examples are objects . Object is a general term .
* Instance and object are a synonym
* Key value pairs and properties and methods
* stay js The set of key value pairs in is called an object
* If the value is data ( Non function ), Call the key value pair an attribute property
* If the value is a function ( Method ), This key value pair is called a method method
* Parents and children
* Traditional object-oriented languages use classes to implement inheritance . Then there is a parent class , The concept of subclass
* A parent class is also called a base class , Subclasses are also called derived classes
* stay js It's often called a parent object in , Sub object . Base object , Derived objects .
  1. Prototype related concepts

    • The mysterious object is called " Prototype attribute "

      • Mysterious objects are the prototype properties of constructors
      • Prototype for short
    • There is also a certain relationship between mysterious objects and objects created by constructors
      • What is the relationship
      • The object created by the mysterious object against the constructor is called " Prototype object "
      • Prototype for short
    • Objects inherit from their prototypes
      • Object created by constructor Inherited from Prototype properties of the constructor
      • Object created by constructor Inherited from The prototype object of the object
      • The object created by the constructor and the object represented by the prototype property of the constructor are two different objects
        • Members of the prototype , Can be used directly by instance objects
        • That is to say, the instance object directly " contain " Members of the prototype
        • therefore Instance object Inherited from Prototype
        • Such an inheritance is " Prototype inheritance "
  2. Some of the problems
    • {} What is a constructor ?
    • All literal objects have constructors
      • {} Object
      • [] Array
      • /./ RegExp
      • function ... Function

How to use prototypes

Why use prototypes ?

  1. Using the dynamic properties of objects

    • Constructors .prototype.XXX = vvvv;
  2. Use direct substitution
 Student.prototype = {
sayHello: function () {},
study: function () {}
};

Prototype prototype More articles about

  1. Simple understanding javascript The prototype of the prototype

    Prototypes and closures are Js The difficulty of language , This article mainly talks about prototype . Each method has a property that is prototype Every object has an attribute that is _proto_ Once a prototype property or prototype method is defined , Then all the functions instantiated by the constructor are ...

  2. Clone replication can use prototypes ( Prototype) Design patterns

    Today there are prototypes for learning design patterns (Prototype)< Design patterns -- Prototype (Prototype) Pattern >http://www.cnblogs.com/insus/p/4152773.html . To add ...

  3. js The best inheritance mechanism : Using objects to impersonate properties of inherited constructors , Using prototypes prototype Methods that inherit objects .

    js The best inheritance mechanism : Using objects to impersonate properties of inherited constructors , Using prototypes prototype Methods that inherit objects . function ClassA(sColor) { this.color = sColor; } Class ...

  4. class (class)、 Constructors (constructor)、 Prototype (prototype)

    class Class The concept of class should be a feature of object-oriented language , however JavaScript Don't like Java,C++ Have formal classes like high-level languages , Most of them are imitated by constructors and prototypes . Before we talk about constructors and prototype methods , I can ...

  5. Prototype prototype -- In depth understanding of javascript

    /* Prototype Prototype */ // One . Prototype // The prototype uses a var calculator = function (dlg, tax) { this.dlg = dlg; this.tax = t ...

  6. Understanding Javascript And Prototype prototype

    Constructor's Prototype The methods defined on can indeed be called directly through objects , And the code is shared . I said I didn't understand . It's hard to understand , acutely . stay Javascript in ,prototype Not only can the object share their wealth , and proto ...

  7. JS Prototype ,Prototype, Prototype

    about javascript Such a front-end language , Personally feel , To really understand it oop, We have to make it clear javascript The object of , Prototype chain , Scope , Closure , as well as this The concept of object and so on . These have made sense to , It should be ...

  8. Prototype prototype、 Prototype chain __proto__、 Constructors constructor

    When creating a function , There will be prototypes prototype, There is a prototype chain __proto__, Yes constructor.( Except for constructors , There is no prototype ) . prototype Prototype : Is an attribute of an object ( Also object ), Enables you to add ...

  9. Prototype (Prototype) Pattern

    The prototype pattern belongs to the object creation pattern . Give a prototype object to indicate the type of all created objects , Then create more objects of the same type by copying the prototype object . That's what the archetypal pattern is about . The structure of the prototype pattern The prototype pattern requires an object to implement a “ clone ...

Random recommendation

  1. Nginx in FastCGI Configuration optimization

    FastCGI: FastCGI It's from CGI Developed and improved . Tradition CGI The main drawback of interface mode is poor performance , Because every time HTTP When the server encounters a dynamic program, it needs to restart the script parser to perform the parsing , The result is then returned to HTTP The server ...

  2. BZOJ1485: [HNOI2009] Interesting sequence

    Description We call a length 2n It's interesting , If and only if the sequence satisfies the following three conditions : (1) It's from 1 To 2n common 2n An arrangement of integers {ai}: (2) All odd terms satisfy a1<a3<…&l ...

  3. java web Code

    primary  30 set JSP Website source code collection IT Little white Release time : 2012/12/28 14:30 read : 272 Collection : 3 give the thumbs-up : 0 Comment on : 0 JSP Technology is based on Java Language as a scripting language ,JSP Web pages for the whole ...

  4. CGContextRef A little usage

      quartz It's the main drawing interface , Support path based drawing . Antialiasing rendering . Gradient fill mode . Images . Color . Coordinate space transformation . as well as PDF Document creation . Show . And analysis .UIKit by Quartz Image and color manipulation provides Ob ...

  5. Application Python Language writing gets Linux Basic system information ( Two ): File system usage capture

    This article continues with the previous article , Link to previous article Application Python Language writing gets Linux Basic system information ( One ): get Linux edition . kernel . current time One . Just talk about The way to get the usage of file system and the main system in the previous article are ...

  6. ViEmu For VS2010 3.0 relieve 30 The method of day limit

    One . summary First ,ViEmu The trial version will record the installation time when it is installed , Time used to determine whether a limit has passed , This time is recorded in the registry With my machine (WIN7X64) For example , It's recorded in HKEY_CLASSES_ROOT\Wo ...

  7. i++ And ++i trap

    about ++i And i++ Programming is essential , The difference between them : Most people only know ++i First of all i I'm going to do other things over and over again ,i++ First of all i Other operations , Add one more . But for i++ The execution process , The language environment is the key . Let's start with two procedures , It turns out that ...

  8. tortoiseGit Save user name and password

    brief introduction :tortoiseGit( Tortoise git) It's graphical git, It's very convenient for us to use , But when we pull private projects , It's cumbersome to enter a user name and password every time , Here's how to avoid how much input Test environment :window10, install ...

  9. uoj#228 Basic data structure exercises

    Topic :http://uoj.ac/problem/228 Positive solution : Line segment tree . We can find out , When the root is opened, the numbers in an interval always tend to be equal . Judge whether the numbers of an interval are equal , Just judge whether the maximum and minimum are equal . If this interval ...

  10. SSRF Vulnerability to learn

    SSRF SSRF(Server-Side Request Forgery: Server side Request Forgery ) It is a security vulnerability that is constructed by the attacker to form a request initiated by the server . In general ,SSRF The target of the attack is from the Internet can not access the inside ...