JavaScript Advanced Programming 6 object-oriented programming of learning notes

Source: Internet
Author: User
Tags uppercase letter

First, JavaScript is not the concept of class.

ECMA-262 defines an object as: "A collection of unordered attributes whose properties can contain basic values, objects, or functions"

Methods for creating objects:

var New  = "Niko"=function() {alert (this. name);};

The above example uses the object literal syntax to write:

var person ="Niko"thefunction() {alert (this. name);}};

Although the object constructor or object literal can be used to create a single object, there are obvious drawbacks to using the same interface to create many objects, resulting in a lot of duplicated code, and in order to solve this problem, people are starting to use a variant of the factory pattern

The factory pattern abstracts the examples of process implementations that create concrete objects as follows

functionvarnew=age ;   =function() {alert (  This return o;//returns the object}

Constructor mode: By convention, constructors should always start with an uppercase letter, while non-constructors should start with a lowercase letter

The above code can be written this way using the constructor pattern:

functionthis. Name =the. Age =this. Job =   thisfunction() {   alert (this. name);}   ;}

Problems with constructors:

The main problem with constructors is that each method is recreated on each instance, because the function in ECMAScript is an object, so there is no function defined, that is, an object is instantiated

Of course, we can do it like this. Move the function definition outside the constructor to solve the problem

functionthis. Name =the. Age =this. Job =   this. sayname = sayname;} function Sayname () {alert (this. name);}

In this example, we set the Sayname property to the global Sayname property inside the constructor, because Sayname contains a pointer to a function, so person1 and Person2 share the same sayname defined in the global scope () The function does this again: a function defined in the global scope can actually be called only by an object, which makes the global scope a bit of a misnomer, even more unacceptable, if you want to define many methods, you need to define a number of global functions

Prototype mode:

Each function we create has a prototype property, which is a pointer to an object that is used to contain properties and methods shared by all instances of a particular type, and the advantage of using a prototype object is that it allows all object instances to share the properties and methods it contains

function= "Niko"="Software engineer"function() {alert (  this. name);};

The hasOwnProperty () method can detect whether a property is in an instance of an object

Prototype and in operator: When used alone, the in operator returns True when the given property is accessible through the object, whether the attribute is present in the instance or in the prototype

To get all instance properties that can be enumerated on an object, you can use the ECMAScript Object.keys () method to receive an object as a parameter, returning an array of strings containing all the properties that can be enumerated

Simpler prototype syntax:

The preceding example does not add a property or method to knock it over again person.prototype to reduce the need for input, you can do this

function= {  "Niko";   ;   function () {alert (this. name);}   }

The dynamic nature of the prototype:

Because the process of looking up values in a run is a search, any modifications made by our team prototype object can be immediately reflected from the instance-even if the prototype was modified before the instance was created

var New  function//"HI"

When we call Friend.sayhi () She will first search for a property named Sayhi from the instance, and will continue to search for the prototype if it is not found, because the link between the instance and the prototype is simply a pointer, not a pointer to a replica instance pointing only to the prototype, not to the constructor

function Person () {} var New  ="Niko"function() {alert ("THIS.name"//  Error

This is because the rewrite prototype object cuts off the connection between the existing prototype and any object instances that existed before, and they refer to the original prototype.

Prototypes of native objects

The importance of the prototype pattern is not only in the creation of custom types, but even the reference types of all the soundtracks are created in this pattern, and all the OST reference types (Object,string,array, etc.) define the methods on the prototype of their constructors.

Problem with prototype object:

The biggest problem with the prototype pattern is that all of the properties in the prototype are shared by many instances, which is very appropriate for the function, and for those that contain the base value, but for attributes that contain reference type values, the problem is more prominent.

 function   person () {}person.prototype  ={constructor:person,name: "Niko", Age: "friends:[", "Shelby", "Sansa"],sayname: function  {Alert (this  .name);}};  var  person1 = new   person ();  var  person2 = new   person ();p Erson1.friends.push ( "Van"  // shelby,sansa,van  alert (person2.friends); // shelby,sansa,van  

Again The Person.prototype object has a property named friends, which contains an array of strings, then creates an instance of two person, then modifies an array of person1.friends references and adds a string to the array, since the friends array exists in the PE Rson.prototype and not Person1, so the changes we just mentioned will be reflected by Person2.friends. However, instances generally have their own properties, so that's why few of us see the use of prototype patterns.

Combining the constructor pattern with the prototype pattern

The most common way to create a custom type is to combine the constructor pattern with the prototype pattern, the constructor pattern to define the instance properties, and the prototype pattern to define the methods and shared properties, with the result that each instance has a copy of the instance properties, but also shares the reference to the method. Maximum savings in memory

functionPerson (name,age,job) { This. Name =name; This. Age =Age ; This. Job =job; This. friends=["Shelly", "Sansa"];}//this is in constructor mode, and each instance initializes the method in the constructor modePerson.prototype ={constructor:person,sayname:function() {Alert ( This. name);}}varPerson1 =NewPerson ();//three parameters are passed herevarPerson2 =NewPerson ();//three parameters are also passed herePerson1.friends.push ("Van"); alert (person1.friends);//Shelly Sansa vanalert (person2.friends);//Shelly Sansa

Inheritance: ECMAScript only supports implementation of inheritance

Prototype chain: The basic idea of a prototype chain is to use a prototype to allow a reference type to inherit another reference type to implement the prototype chain there is a basic way of code that is roughly the following

functionSupertype () { This. property=true;} SuperType.prototype.getSuperValue=function(){return  This. property};functionSubtype () { This. Subproperty =false;} Subtype.prototype=NewSupertype ();//inherited the supertype.Subtype.prototype =Newsupertype (); SubType.prototype.getSubValue=function(){return  This. Subproperty;};varInstance =Newsubtype (); alert (Instance.getsupervalue ());//true

Problem with the prototype chain:

 function   Supertype () { this . colors=["Red", "green"  function   subtype () {} Subtype.prototype  = new   Supertype ();  var  Instance1 =  subtype (); Instance1.colors.push ( black " // red.green.black  var  instance2 =  subtype (); alert (intance2.colors);  // red Green black  

Using constructors to implement inheritance: this is called pseudo-inheritance or classic inheritance

function Supertype () {this. colors=["Red", "Blue"];} function Subtype () {Supertype.call (this);} var New subtype (); Instance1.colors.push("Black"); alert (instance1.colors) ; // Red Blue Black var New subtype (); alert (instance2.colors); // Red Blue

Combination Inheritance:

function Supertype (name) {this.name = Name;this.colors = ["Red", "Blue"];} SuperType.prototype.sayName = function () {alert (this.name);}; Function subtype (name,age) {supertype.call (this,name);//inheritance Property This.age = age;} Inheritance method Subtype.prototype = new Supertype (); SubType.prototype.constructor = subtype (); SubType.prototype.sayAge = function () {alert (this.age);}; var Instance1 = new Subtype ("Niko"); Instance1.colors.push ("Black"); Instance1.sayname ();//nikoinstance1.sayage () ;//20var Instance2 = new Subtype ("Sansa", N); alert (instance2.colors); Instance2.sayname ();//sansainstance2.sayage () ;//29

  

JavaScript Advanced Programming 6 object-oriented programming of learning notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.