Object-oriented programming of JavaScript design patterns (object-oriented Programming,oop) (ii)

Source: Internet
Author: User
Tags closure



Pick up an article



An understanding of object-oriented programming?



A: Object-oriented programming is to abstract your requirements into an object and then analyze its characteristics (attributes) and actions (methods) against this object. This object we call class. One of the features of object-oriented programming is encapsulation, which is to put the function you need in an object.






First, the package



1.1 Creating a class



Creating a class in JavaScript is easy,



method One: first, declare a function to be stored in the variable, and then, within the function through this (inside the function of a variable, used to point to the current object) variable to add a property or method to the class to implement the addition of properties or methods.



As an example:


 
 
var Book = function(id,bookname,price){
  this.id = id;
  this.bookname = bookname;
  this.price = price;      
}


Method Two: You can add properties or methods through the prototype of a class, there are a couple of methods, do not mix



(1) Methods for assigning values to the properties of a prototype object


Book.prototype.display = function () {
     // show this book
}; 


(2) Assigning an object to a prototype object of a class


Book.prototype = {
    display:function(){}
};





The methods and properties we need are encapsulated in our abstract book class, and when we use the function method, we can't use the book class directly, we need to instantiate the new object with the keyword new. When you use a property or method that instantiates an object, you can access it through the point syntax


 
var book = new Book(10,‘javascript课本‘,50);
console.log(book.bookname);


Because of the function-level scope of JavaScript, the variables and methods declared inside the function are not accessible to the outside world, and this attribute allows you to create private variables and private methods of the class. However, the properties and methods created inside the function through this, each object has one copy and can be accessed externally when the class creates the object. Therefore, this is created to not only access the common properties and common methods of these objects, but also to access the private properties and private methods of the class or the object itself.


// Private property, private method; privileged method, object public property, object public method; constructor
var Book = function (id, name, price) {
     // Private property
     var num = 1;
     // Private method
     function checkId () {};
    
     // Privileged method
     this.getName = function () ();
     this.getPrice = function () ();
     this.setName = function () {};
     this.setPrice = function () ();

     // Object public properties
     this.id = id;
     // Object public method
     this.copy = function () {};

     // constructor
     this.setName (name);
     this.setPrice (price);
}; 


Use the native prototype object.


// Static public property (object cannot be accessed)
Book.isChinese = true;

// Class static public method (object cannot be accessed)
Book.resetTime = function () {
     console.log (‘new time’);
};

Book.prototype = {
         // public property
     isJSBook: false,
     // public method
     display: function () {}
}


The object created by the New keyword is continuously assigned to this, and prototype points to the object that the class prototype points to, and the property method outside the class's constructor that is defined by the point syntax is not added to the newly created object.


var b = new Book (11, ‘JavaScript Design’, 50);
console.log (b.num); // undefined
console.log (b.isJSBook); // false
console.log (b.id); // 11
console.log (b.isChinese); // undefined 


The private property of the class num, as well as the static public property Ischinese, is not accessible in the newly created B object. The public property of the class, Isjsbook, can be accessed through the point syntax in the B object.



However, the static public property of a class Ischinese can be accessed through the class itself.


console.log(Book.isChinese);   //true
Book.resetTime();    //new time
 

 





1.2 Closure implementation



What's your understanding of closures?



A: A closure is a function that has access to a variable in another function scope, that is, creating another function inside a function . We use this closure as the constructor for creating objects, so that it is a function of a closed and instantiated object that accesses variables of class function scope, called static private variables, static private methods.






Ii. inheritance



Summary class: Discover that each class has 3 parts:



1, the first part is in the constructor function, for the instantiation of the object replication;



2, the second part is the constructor , directly through the point syntax is added, which is used for the class, the object is not accessed when instantiating;



3, the third part is the prototype of the class , the instantiation of the object can be indirectly accessed through its prototype chain, but also for all the instantiated objects common.



JavaScript does not inherit this existing mechanism, how to implement it?






(i) prototype objects of subclasses--class-like inheritance



For example: Common Class-Type inheritance


// class inheritance
// Declaring the parent class
function SuperClass () {
     this.superValue = true;
}
// Add a common method for the parent class
SuperClass.prototype.getSuperValue = function () {
     return this.superValue;
};

// Declaring subclasses
function SubClass () {
     this.subValue = false;
}

// Inherit the parent class
SubClass.prototype = new SuperClass ();

// Add common methods for subclasses
SubClass.prototype.getSubValue = function () {
     return this.subValue;
} 


Just encapsulation, contrast, inheritance declares 2 classes, and the second class's prototype prototype is given an instance of the first class.



Class inheritance requires that an instance of the first class be assigned to a prototype of a second class.



Inheritance principle: newly created objects can access not only properties and methods on the parent prototype, but also properties and methods copied from the parent class constructor. By assigning this object to the prototype of the subclass, the prototype of the subclass can also access the properties and methods on the parent prototype as well as the properties and methods copied from the parent class constructor.


 
var instance = new SubClass();
console.log(instance.getSuperValue());   //true
console.log(instance.getSubValue());     //false





In JS, there is a keyword instanceof to determine whether an object is an instance of a class, or whether an object inherits a class, which can be used to determine the relationship between an object and a class.



How does instanceof know the inheritance between objects and classes?



Instanceof is to determine whether the object is an instance of a class by judging the prototype chain of the object, without caring about the structure of the object and the class itself.


 
console.log(instance instanceof SuperClass);   //true
console.log(instance instanceof SubClass);   //true
console.log(SubClass instanceof SuperClass);  //false


Why the last is false,subclass inherit superclass, why or false; remember:instanceof is the instance that determines whether the preceding object is a back Class (object), and it does not represent an inheritance of both.


instanceof // true





One of the characteristics of class inheritance: whose instances are all the objects you create?



Object, the official JavaScript provides us with the native objects object. all objects created are instances of object.


instanceof // true


There are two disadvantages to class-type inheritance:



1, because the subclass is instantiated by its prototype prototype to the parent class, inherits the parent class. So the parent class has properties that, if the reference type, is shared by all instances in the subclass, so that an instance of a subclass changes the common attribute inherited from the parent class constructor directly affects the other subclasses.



2, because the subclass implementation of the inheritance is by the prototype of the prototype of the parent class is implemented, so when the parent class is created, the parent class cannot be passed parameters, so when the parent class is instantiated, the properties within the parent class constructor cannot be initialized.






(ii) Creation is inheritance--the inheritance of constructor function



constructor inheritance in addition to class-Type inheritance


// Constructor-style inheritance
// Declaring the parent class
function SuperClass (id) {
     // Reference type common attributes
     this.books = [‘JavaScript’, ‘html’, ‘css’];
     // Value type common attributes
     this.id = id;
}

// Method of parent class declaration prototype
SuperClass.prototype.showBooks = function () {
     console.log (this.books);
}

// Declaring subclasses
function SubClass (id) {
     // Inherit the parent class
     SuperClass.call (this, id);
}

// Create an instance of the first subclass
var instance1 = new SubClass (10);
// Create an instance of the second subclass
var instance2 = new SubClass (11);

instance1.books.push (‘Design Pattern’);
console.log (instance1.books); // ["JavaScript", "html", "css", "Design Mode"]
console.log (instance1.id); // 10
console.log (instance2.books); // ["JavaScript", "html", "css"]
console.log (instance2.id); // 11 


Note: Superclass.call (this.id); This statement is the essence of constructor-style inheritance, because call this method can change the scope of the function ,



Since this type of inheritance does not involve the prototype prototype, the prototype method of the parent class naturally does not inherit the quilt class, and if you want the quilt class to inherit it must be placed in the constructor, so that every instance created will have a copy and cannot be shared, which violates the principle of code reuse.



The advantages of these two models, and then there is a combination of inheritance






(iii) Set advantages--Combined inheritance



To summarize:



(1) class-type inheritance, which is implemented by prototype the parent class through the prototype of the subclass.



(2) constructor inheritance, implemented by the constructor function of the subclass to execute the constructor of the parent class.


// Combined inheritance
// Declaring the parent class
function SuperClass (name) {
     // Value type common attributes
     this.name = name;
     // Reference type common attributes
     this.books = [‘html’, ‘css’, ‘JavaScript’];
};

// Shared methods of the parent prototype
SuperClass.prototype.getName = function () {
     console.log (this.name);
};

// Declaring subclasses
function SubClass (name, time) {
     // Constructor-style inheritance of the parent class name attribute
     SuperClass.call (this, name);
     // New common attributes in subclasses
     this.time = time;
}

// class inheritance
SubClass.prototype = new SuperClass ();
// Subclass prototype method
SubClass.prototype.getTime = function () {
     console.log (this.time);
} 


Combined Mode: Executes the parent class constructor in the subclass constructor and instantiates the parent class on the subclass prototype.



This blends the benefits of class-and constructor-inheritance.


var instance1 = new SubClass (‘js book ′, 2014);
instance1.books.push (‘Design Pattern’);
console.log (instance1.books); // ["html", "css", "JavaScript", "Design Mode"]
instance1.getName (); // js book
instance1.getTime (); // 2014

var instance2 = new SubClass (‘css book’, 2013);
console.log (instance2.books); // ["html", "css", "JavaScript"]
instance2.getName (); // css book
instance2.getTime (); // 2013 


Changing the reference type attributes inherited by the parent class in an instance of the subclass, such as books, does not affect other instances at all.



However, when we use constructor inheritance, we execute the constructor of the parent class once, and then call the constructor of the parent class again when we implement the subclass inheritance of the subclass prototype. so the parent class constructor was called two times , not the perfect way.






(iv) The successor of cleanliness--prototype inheritance



With the prototype of the prototype, you can create a new object from an existing object without having to create a new custom object type.


var inheritObject (item) {
     // Declaring a transition function object
     function F () {};
     // The prototype of the transition object inherits the parent object
     F.prototype = item;
     // Return an instance of the transition object, the prototype of this instance inherits the parent object
     return new F ();
} 


He is an encapsulation of class inheritance, in fact, the transition object is equivalent to the subclass in the class inheritance, but in the prototype as a transitional object appears, in order to create to return the new instantiated object.



Of course, if you feel the need to cache the F transition, you don't have to create a new transition class F each time, and then the Object.create () method appears.


 
var book = {
    name: ‘js book‘,
    alikeBook: [‘css book‘,‘html book‘],
}; var newBook = inheritObject(book);
newBook.name = ‘ajax book‘;
newBook.alikeBook.push(‘xml book‘); var otherBook = inheritObject(book);
otherBook.name = ‘flash book‘;
otherBook.alikeBook.push(‘as book‘);

console.log(newBook.name); //ajax book console.log(newBook.alikeBook); //[‘css book‘,‘html book‘,‘xml book‘,‘as book‘]  console.log(otherBook.name); //flash book console.log(otherBook.alikeBook); //[‘css book‘,‘html book‘,‘xml book‘,‘as book‘]  console.log(book.name); //js book console.log(book.alikebook); //[‘css book‘,‘html book‘,‘xml book‘,‘as book‘] 


As with class inheritance, the properties of the value types in the parent object book are copied, and the properties of the reference type are shared.






Object-oriented programming of JavaScript design patterns (object-oriented Programming,oop) (ii)


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.