Object-oriented knowledge in javascript detail

Source: Internet
Author: User
Tags extend inheritance instance method

Object-oriented, JS put all the objects into the object type, so that JS has 6 types of data users can use. In addition to the UNDEFINED,JS for all types of literals (literal) syntax, now, JS's object face value represents a very successful design, and now even become a data interchange format, which is familiar with the JSON. A Sample:

var atshirt={color: "Yellow", Size: "Big"} as a dynamic language, JS allows the user to add or remove attributes to an object that has already been created. The property is added to a nonexistent property assignment, and the DELETE keyword is used to delete the property. This delete is more likely to be confused with the C + + delete operator, which is used to release objects that are no longer in use.

With these syntax, you can already do basic object-oriented programming, but just so, JS code reusability is much weaker than other languages. For example, you can't even do a unified operation for a group of objects, you have to iterate through the loop to achieve, so JS introduced the prototype (prototype), the specific implementation is to specify a private property for each object [[prototype]], when reading an object's properties, If the object itself does not have this property, it attempts to access the corresponding property of [[prototype]]. In a concrete implementation, [[prototype]] can still have [[prototype]], the actual access is a chained operation until this property is found or [[prototype]] is empty, so often hear the [[prototype]] chain. To prevent the [[prototype]] from appearing loops, the JS engine checks for any object's [[prototype]] property being modified.

By standard, this [[prototype]] language user is inaccessible, but the Firefox JS engine exposes [[prototype]] as a public property "__proto__" so that we can manipulate the behavior of a group of objects by manipulating the prototype object. We can borrow the convenience provided by FF to understand how [[prototype]] works:

The code is as follows Copy Code
var proto={a:1};
var m={__proto__:proto};
var n={__proto__:proto};
alert ([M.a,n.a]);
proto.a=2;
alert ([M.a,n.a]);


JS sets a built-in object as the final [[prototype]] of all objects, that is, an object created using {}, and [[prototype]] points to the built-in object.

With this mechanism, we are able to achieve a considerable degree of object reuse with a class-based language-but of course we need a function. In JS, the function is only a special object, JS designed () operator and function keyword to make JS functions look more like the traditional language. As long as the object that implements the private method [[call]] is considered to be a function object (this [[call]] is completely different from the familiar Function.prototype.call), similar to [[Prototype]],[[call]] is also completely inaccessible to language users, and this time FF did not provide us with a public attribute to replace it.

Ben came here so far, JS object-oriented has been very complete, but JS in order to make their own syntax looks more like Java language, and introduced the New keyword, in most of the language of the new is done for the class, and JS does not have classes, and even did not declare the domain, So this new is going to make a fuss over the object, and new will call the private method [[Contruct]], and any object that implements [[construct]] can be accepted by new. But how do you get an object to be new? JS does not provide additional constructs for this object method, so all function objects constructed from the Functions keyword are designed to implement the [[construct]] method. This is also the reason that JS's new is very strange for functions. It is worth mentioning that not only functions can be NEW,JS hosting environment may provide some other objects, the typical example is the ActiveXObject in IE.

The [[construct]] methods for all functions are similar: Create a new object, set its [[prototype]] as a common property of the Function object prototype, take the new object as the value of this pointer, and execute the function object

This creates a similar object in fact for the new operation of the same function: having a common prototype [[prototype]], which is handled by the same function. This new operation is very similar to class, at the same time because of the dynamic nature of JS, all the "class" in the run when you slaughter, want to simulate the behavior of inheritance and so easy, because it is weak type and dynamic function, there is no need for polymorphic problems, JS can be done based on class-oriented object-oriented

First, packaging

Object definition: ECMA-262 defines an object as: "A collection of unordered attributes, where properties can include basic values, objects, or functions."

Create object: Each object is created from a reference type that can be a primitive type (object, Array, Date, RegExp, Function, Boolean, Number, String), or a custom type.

1, the constructor function pattern

The code is as follows Copy Code
function person (name, age) {
THIS.name = name;
This.age = age;
This.sayname = function () {
alert (this.name);
}
}

Use the new operator with the above constructor to create an object instance.

The code is as follows Copy Code
var Zhangsan = new Person (' Zhangsan ', 20);
var lisi = new Person (' Lisi ', 20);
Zhangsan.sayname ();//zhangsan
Lisi.sayname (); Lisi 4 steps to create an object through new

1. Create a new object; [var o = new Object ();]

2. Assign the scope of the constructor to the new object (so this points to the new object); [Person.apply (O)] [person's original this is pointing to window]

3, execute the code in the constructor (add attributes for this new object);

4, return the new object.

To restore new by code:

The code is as follows Copy Code
function Createperson (P) {
var o = new Object ();
var args = Array.prototype.slice.call (arguments, 1);
o.__proto__ = P.prototype;
P.prototype.constructor = P;
P.apply (o, args);
}

To test a new creation instance method

The code is as follows Copy Code
var Wangwu = Createperson (person, ' Wangwu ', 20);
Wangwu.sayname ();//wangwu2, prototype mode

Prototype Object concept: Whenever you create a new function, you create a prototype attribute for the function based on a specific set of rules, which points to the prototype object of the function. By default, all prototype objects will automatically get a constructor (constructor) property that contains a pointer to the function where the prototype property is located. With this constructor, you can continue to add additional properties and methods to the prototype object. When a custom constructor is created, its prototype object only obtains the constructor property by default, and the other methods inherit from object. When the constructor is called to create a new instance, the internal of the instance will contain a pointer (internal property) that points to the stereotype object of the constructor. ECMA-262 5th Edition Tube This pointer is called [[Prototype]]. There is no standard way to access [[Prototype]] in the script, but Firefox, Safari, and chrome support a property __proto__ on each object, and in other implementations, this property is completely invisible to the script. However, the really important point to be clear is that the connection exists between the sample and the stereotype object of the constructor, not between the instance and the constructor.

This section basically outlines the relationship between constructors, prototypes, and examples, and the following illustration shows a clearer

The code is as follows Copy Code
function person (name, age) {
THIS.name = name;
This.age = age;
}
Person.prototype.country = ' Chinese ';
Person.prototype.sayCountry = function () {
alert (this.country);
}

var Zhangsan = new Person (' Zhangsan ', 20);
var lisi = new Person (' Lisi ', 20);

Zhangsan.saycountry (); Chinese
Lisi.saycountry (); Chinese


Alert (Zhangsan.saycountry = = Lisi.saycountry); True Note place: The prototype object of the constructor, the primary purpose is to have multiple object instances share the properties and methods it contains. But this is also a problem prone place, if the prototype object contains reference types, then the type should be referenced by the pointer, so it will result in value sharing. As follows:

The code is as follows Copy Code

Person.prototype.friends = [' Wangwu ']; Person to add an array type
Zhangsan.friends.push (' Zhaoliu '); John Modification will affect dick
alert (zhangsan.friends); Wangwu,zhaoliu
alert (lisi.friends); Wangwu,zhaoliu Dick is also 3, combining the constructor pattern with the prototype schema

This pattern is the most widely used and most agreeable way to create a custom type. The constructor pattern is used to define instance properties, which are used to define methods and shared properties. In this way, each instance has its own copy of the instance attribute, and there is a shared reference to the method, saving the maximum amount of memory.

The prototype model is modified as follows:

The code is as follows Copy Code
function person (name, age) {
THIS.name = name;
This.age = age;
This.friends = [' Wangwu '];
}

Person.prototype.country = ' Chinese ';
Person.prototype.sayCountry = function () {
alert (this.country);
}

var Zhangsan = new Person (' Zhangsan ', 20);
var lisi = new Person (' Lisi ', 20);

Zhangsan.friends.push (' Zhaoliu ');
alert (zhangsan.friends); Wangwu,zhaoliu
alert (lisi.friends); Wangwu

Second, the succession

Inheriting basic concepts

ECMAScript relies primarily on prototype chains to implement inheritance (or it can be inherited by copying attributes).

The basic idea of a prototype chain is to make a reference type inherit properties and methods of another reference type using a prototype. The relationship between constructors, prototypes, and samples is that each constructor has a prototype object that contains a pointer to the constructor, and the instance contains an internal pointer to the prototype. So, by having the prototype object equal to an instance of another type, the prototype object will contain a pointer to another prototype, and, correspondingly, a pointer to another constructor is included in the other prototype. If another prototype is another type of instance, then the relationship is still set up, so the level of progression, forming the chain of examples and prototypes. This is the basic concept of the prototype chain.

It's not easy to understand if you read it around. The validation is demonstrated directly through an instance.

1. Prototype chain inheritance

  code is as follows copy code
function Parent () {
    this.pname = ' parent ';
}
Parent.prototype.getParentName = function () {
    return this.pname;
}
 
Function Child () {
    this.cname = ' child ';
} The
///Sub constructor prototype is set to an instance of the parent constructor, forming a prototype chain, allowing the child to own the Getparentname method
Child.prototype = new parent ();
Child.prototype.getChildName = function () {
    return this.cname;
}
 
var c = new Child ();
Alert (C.getparentname ());//parent

The problem with the prototype chain is that if a reference type is included in the parent class, the reference type in the parent class is brought to the prototype of the subclass by Child.prototype = new parent (), and the prototype property of the reference type value is shared by all instances. The question is back to [A, 2] section.

2, combined inheritance-the most common way to inherit

Combined inheritance (combination inheritance) is a combination of prototype chains and borrowed constructors (apply, call) techniques. The idea is to implement the inheritance of prototype properties and methods using the prototype chain, and to inherit the instance property by borrowing the constructor. In this way, the method can be defined on the prototype to realize the reuse of functions and to ensure that each instance has its own attributes.

The code is as follows Copy Code
function Parent (name) {
    this.name = name;
    this.colors = [' Red ', ' yellow '];
}
Parent.prototype.sayName = function () {
    alert (this.name);
}
 
Function Child (name, age) {
    parent.call (this, name);//The second call to Parent ()
 &N bsp;  this.age = age;
}
 
Child.prototype = new parent ();//First Call parent (), the parent class's properties
Child.prototype.sayAge = function () {
    alert (this.age);
}
 
var c1 = new Child (' Zhangsan ';
var c2 = new Child (' Lisi ');
C1.colors.push (' Blue ');
Alert (c1.colors);   //red,yellow,blue
C1.sayname ();   //zhangsan
C1.sayage ();   //20
 
Alert (c2.colors);//red,yellow
C2.sayname ();//lisi
C2.sayage ();

The problem with combinatorial inheritance is that you call a two-time superclass constructor at a time: the first time you create a subtype prototype, and the other one is inside the subtype constructor. This results in an override of the property, which contains the properties of the parent class, and the subclass's prototype object also contains the properties of the parent class.

3, parasitic combination inheritance-the most perfect way to inherit

The so-called parasitic combination inheritance, that is, by borrowing the constructor to inherit the property, through the prototype chain of the hybrid form to inherit the method. The basic idea behind it is that you don't have to call a superclass constructor to specify the stereotype of a subclass, all we need is a copy of the Super type prototype.

The code is as follows Copy Code

function extend (child, parent) {
var F = function () {}; To define an empty constructor
F.prototype = Parent.prototype; Set as a prototype of the parent class
Child.prototype = new F (); The prototype of the subclass is set to an instance of F to form a prototype chain
Child.prototype.constructor = child; Re-specifying the subclass constructor pointer
}

function Parent (name) {
THIS.name = name;
this.colors = [' Red ', ' yellow '];
}
Parent.prototype.sayName = function () {
alert (this.name);
}

function child (name, age) {
Parent.call (this, name);
This.age = age;
}

Extend (child, Parent); Implementing inheritance
Child.prototype.sayAge = function () {
alert (this.age);
}

var C1 = new Child (' Zhangsan ', 20);
var C2 = new Child (' Lisi ', 21);

C1.colors.push (' Blue ');
alert (c1.colors); Red,yellow,blue
C1.sayname (); Zhangsan
C1.sayage (); 20
alert (c2.colors); Red,yellow
C2.sayname (); Lisi
C2.sayage (); 21st

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.