JavaScript Object-oriented and prototype

Source: Internet
Author: User
Tags hasownproperty

Factory mode: Object not recognized

function CreateObject (name, age) {//functions that are instantiated in a centralized format
var obj = new Object ();
Obj.name = name;
Obj.age = age;
Obj.run = function () {
Return this.name + this.age + ' running ... ';
};
return obj;
}
var box1 = CreateObject (' Lee ', 100); First Instance
var box2 = CreateObject (' Jack ', 200); A second instance
Alert (Box1.run ());
Alert (Box2.run ()); Remain independent

Alert (typeof Box1); Object
Alert (box1 instanceof Object); True

Constructors (construction methods): objects can be recognized

function Box (name, age) {//constructor mode
THIS.name = name;
This.age = age;
This.run = function () {
Return this.name + this.age + ' running ... ';
};
}
var box1 = new Box (' Lee ', 100); New Box ()
var box2 = new Box (' Jack ', 200);

Alert (Box1.run ());
Alert (box1 instanceof Box); Clearly identified him from the Box

Constructor methods have some specifications:

1. The function name and instantiation construct name are the same and uppercase, (PS: non-mandatory, but it helps to distinguish between constructors and ordinary functions);

2. Create an object from a constructor, you must use the new operator.

var o = new Object ();
Box.call (o, ' Jack ', 200)//Object Impersonation Call
Alert (O.run ());

Prototype (shared): Each function created has a prototype (prototype) attribute, which is an object whose purpose is to contain properties and methods that can be shared by all instances of a particular type. This is logically understood: prototype the prototype object of the object that was created by invoking the constructor. The benefits of using prototypes allow all object instances to share the properties and methods that it contains. That is, instead of defining the object information in the constructor, you can add the information directly to the prototype.

Unction Box () {}//Declare a constructor
Box.prototype.name = ' Lee '; Adding attributes to a prototype
Box.prototype.age = 100;
Box.prototype.run = function () {//Add method in prototype
Return this.name + this.age + ' running ... ';
};

In the prototype schema declaration, there are two more properties, both of which are generated automatically when the object is created.

__proto__ property: Is a pointer to the prototype object that the instance is pointing to, which is the prototype property constructor of the constructor. With these two properties, you can access the properties and methods in the prototype.

Ps:ie browser in script access __proto__ will not be recognized, Firefox and Google Browser and some other browsers can be recognized. Although it can be output, it cannot get internal information.

Determines whether an object points to a prototype object of the constructor, which can be tested using the isPrototypeOf () method.

Exp:alert (Box.prototype.isPrototypeOf (Box)); Whenever an object is instantiated, it will point to the

The execution flow of the prototype pattern:
1. First find the property or method in the constructor instance, and if so, return immediately;
2. If not in the constructor instance, go to its prototype object, and if so, return;

Although we can access the values saved in the prototype through the object instance, we cannot access the values in the prototype rewrite through the object instance.

var box1 = new Box ();
alert (box1.name); Lee, the value in the prototype.
Box1.name = ' Jack ';
alert (box.1name); Jack, the nearest principle,
var box2 = new Box ();
alert (box2.name); Lee, the value in the prototype, hasn't been box1 modified.
If you want to Box1 can also continue to access the values in the prototype, you can delete the properties in the constructor, as follows:
Delete Box1.name; Delete Property
alert (box1.name);
How can I tell if a property is in an instance of a constructor or in a prototype? You can use the hasOwnProperty () function to verify that:

Alert (Box.hasownproperty (' name ')); Returns true in the instance, otherwise false

The In operator returns True when the given property is accessible through the object, regardless of whether the attribute exists in the instance or in the prototype.
Alert (' Name ' in box); True, exists in the instance or in the prototype
We can detect whether an attribute exists in an instance by using the hasOwnProperty () method, or it can be used to determine whether an attribute exists in an instance or prototype. The combination of these two methods allows you to determine whether a property exists in the prototype.

function Isproperty (object, property) {//To determine if an attribute exists in the prototype
Return!object.hasownproperty (property) && (object);
}

var box = new box ();
Alert (Isproperty (box, ' name '))//true, if the prototype has

In order for properties and methods to better reflect the effects of encapsulation, and to reduce unnecessary input, prototypes can be created in a literal way:

function Box () {};
Box.prototype = {//Use the literal way
Name: ' Lee ',
AGE:100,
Run:function () {
Return this.name + this.age + ' running ... ';
}
};

Using constructors to create prototype objects and to create objects using literals is basically the same, but there are some differences in the way that literal creation uses the constructor property to not point to an instance, but to object, which is the opposite of how the constructor is created.

If you want the constructor of the literal way to point to an instance object, you can do this:
Box.prototype = {
Constructor:box,//direct force pointing can be
};

Prototype objects can be used not only in the case of custom objects, but also in ECMAScript built-in reference types, and the built-in reference types themselves use prototypes.

alert (Array.prototype.sort); Sort is the prototype method of the Array type
alert (String.prototype.substring); SUBSTRING is the prototype method of String type
String.prototype.addstring = function () {//Add a method to the String type
Return this + ', was added! ‘; This represents the string that is called
};
Alert (' Lee '. addstring ()); Use this method

PS: Although it is particularly convenient to add methods to native built-in reference types, we do not recommend using this method. Because it can cause naming conflicts, it is not conducive to code maintenance.

Dynamic Prototyping Mode

function Box (name, age) {//encapsulates all information into the function body
THIS.name = name;
This.age = age;
if (typeof this.run! = ' function ') {//Initialize only on first call
Box.prototype.run = function () {
Return this.name + this.age + ' running ... ';
};
}
}
var box = new Box (' Lee ', 100);
Alert (Box.run ());

PS: Using the dynamic prototype mode, be aware that you can no longer use the literal way to rewrite the prototype, because it will cut off the connection between the instance and the new prototype.

Parasitic constructors

function Box (name, age) {
var obj = new Object ();
Obj.name = name;
Obj.age = age;
Obj.run = function () {
Return this.name + this.age + ' running ... ';
};
return obj;
}

Secure constructor function

function Box (name, age) {
var obj = new Object ();
Obj.run = function () {
Return name + Age + ' running ... '; Direct printing of parameters can be
};
return obj;
}
var box = box (' Lee ', 100); Calling functions Directly
Alert (Box.run ());

Inheritance: Relying on the prototype chain to complete

function Box () {//box construction
this.name = ' Lee ';
}
function Desk () {//desk construct
This.age = 100;
}
Desk.prototype = new Box (); Desc inherits the Box, through the prototype, forming the chain
var desk = new Desk ();
alert (desk.age);
alert (desk.name); Get the Inherited property
function Table () {//table construct
This.level = ' AAAAA ';
}
Table.prototype = new Desk (); Continuation of the prototype chain inheritance
var table = new Table ();
alert (table.name); Inherited Box and Desk.

In JavaScript, inherited functions are called supertype (parent class, base class, other language), and inherited functions are called subtypes (subclasses, derived classes). Inheritance also has previous problems, such as literal rewriting of a prototype that breaks relationships, uses a prototype of a reference type, and the subtype cannot pass parameters to the super type.

Object Impersonation (Forgery object, classic inheritance, borrowing constructor): Resolves an issue where reference sharing and super type cannot be passed

function Box (age) {
THIS.name = [' Lee ', ' Jack ', ' Hello ']
This.age = age;
}
function Desk (age) {
Box.call (this, age); Object impersonating, giving the super type a parameter

}
var desk = new Desk (200);
alert (desk.age);
alert (desk.name);
Desk.name.push (' AAA '); New data added, only for desk
alert (desk.name);

Combinatorial inheritance: Prototype chain + borrowing constructors

function Box (age) {
THIS.name = [' Lee ', ' Jack ', ' Hello ']
This.age = age;
}
Box.prototype.run = function () {
return this.name + this.age;
};
function Desk (age) {
Box.call (this, age); Object Impersonation
}
Desk.prototype = new Box (); Prototype chain inheritance
var desk = new Desk (100);
Alert (Desk.run ());

Parasitic combination inheritance

function obj (o) {//pass a literal function
function F () {}//temporarily creates a new constructor to store the object passed in
F.prototype = O; Assign an O object instance to the prototype object of the F construct

return new F (); Returns the instantiated constructor
}
function Create (box, desk) {
var f = obj (Box.prototype);
F.constructor = desk;
Desk.prototype = f;
}
function Box (name) {
THIS.name = name;
This.arr = [' elder brother ', ' sister ', ' parents '];
}
Box.prototype.run = function () {
return this.name;
};
function Desk (name, age) {
Box.call (this, name);
This.age = age;
}
Inprototype (Box, Desk); Inheritance is achieved through this
var desk = new Desk (' Lee ', 100);
Desk.arr.push (' elder sister ');
alert (Desk.arr);
Alert (Desk.run ()); Only methods are shared
var desk2 = new Desk (' Jack ', 200);
alert (Desk2.arr); Reference Problem Resolution

JavaScript Object-oriented and prototype

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.