JS to create an object model introduction __js

Source: Internet
Author: User
Tags object object hasownproperty
var box = new Object ()///Create an object

box.name = ' Lee ';//Create a Name property and assign a value

box.age = 100;//Create an Age attribute and assign

box. Run = function () {//Creates a run () method and returns the value return

THIS.name + this.age + ' run ... ';

Alert (Box.run ());//Output values of properties and methods

The above creates an object and creates properties and methods, which in the run () method represent the box object itself. This is the most basic way for JavaScript to create objects, but there is a drawback that creating a similar object creates a lot of code.

var box2 = box;//Gets the box reference
box2.name = ' Jack ';//directly changed the name attribute
alert (Box2.run ());//Box.run ()
found name changed 
  var box2 = new Object ();
Box2.name = ' Jack ';
Box2.age =;
Box2.run = function () {return
this.name + this.age + ' run ... ';
Alert (Box2.run ());//So as to avoid confusion with box, and thus remain independent 
in order to solve the problem of multiple similar object declarations, we can use a method called Factory mode, which is to solve the problem that the instantiation object produces a lot of repetition.
 function CreateObject (name, age) {//Set instantiated
var obj = new Object ();
Obj.name = name;
Obj.age = age;
Obj.run = function () {return
this.name + this.age + ' run ... ';
return obj;
}
var box1 = CreateObject (' Lee ', MB);
var box2 = CreateObject (' Jack ');
Alert (Box1.run ()); Alert (Box2.run ()); First Instance//second instance//remain Independent

The factory pattern solves the problem of duplicate instantiation, but there is also the problem of identifying the problem, because it is impossible to figure out exactly which object they are an instance of.

Alert (typeof box1);//object
alert (box1 instanceof Object);//true

Constructors (constructors) can be used in ECMAScript to create specific objects. Type to object.

function Box (name, age) {//constructor mode
this.name = name;
This.age = age;
This.run = function () {return
this.name + this.age + ' run ... ';}
var box1 = new Box (' Lee ', m);
var box2 = new Box (' Jack ', 200); New Box ()
alert (Box1.run ());
Alert (box1 instanceof Box); Clearly identified him as belonging to Box

Using the constructor method, it solves the problem of duplicate instantiation, and solves the problem of object recognition, but the problem is, there is no new object (), why can you instantiate Box (), where did this come from? Methods that use constructors, and methods that use factory patterns they differ in the following ways:

1. The constructor method does not display the creation object (new object ());

2. Assign properties and methods directly to the This object;

3. No Renturn statements.

There are some specifications for constructors ' methods:

1. The function name and the instantiated constructor name are the same and uppercase, (PS: not mandatory, but so write to help distinguish between constructors and ordinary functions);

2. To create an object from a constructor, you must use the new operator. Now that you can create an object from a constructor, where does the object come from and where is the new object () executed? The process of execution is as follows:

1. When the constructor is used and the new constructor (), the new Object () is executed in the background;

2. The scope of the constructor is given to the new object (that is, the object that is created by new object), and the This in the body of the function represents the object that came out of the.

3. Execute the code within the constructor;

4. Return the new object (background returned directly).

For the use of this, this is actually a reference representing the current scope object. If this represents a Window object in the global scope, if it is in the constructor body, it represents the object declared by the current constructor.

var box = 2; alert (this.box);//The
only difference between the global representation of the window constructor and the normal function is that they are invoked in a different way. However, a constructor is also a function that must be invoked with the new operator, otherwise it is a normal function.
var box = new Box (' Lee ', 100);//construct mode call
alert (Box.run ());
Box (' Lee ');
var o = new Object ();
Box.call (o, ' Jack ',) alert (O.run ()); Normal mode invocation, invalid//object impersonation Call

To explore the problem of methods (or functions) within a constructor, first look at the equality of the two instantiated properties or methods.

var box1 = new Box (' Lee ', 100);//Pass consistent
var box2 = new Box (' Lee ', 100);/ibid.
alert (box1.name = = Box2.name); Value Equality
alert (Box1.run = = Box2.run);//false, the method is also a reference to address
alert (box1.run () = = Box2.run ());//true, the value of the method is equal because the argument is consistent

You can replace the method (or function) in the constructor with the new function () method to get the same effect, proving that they ultimately judge the reference address, uniqueness.

function Box (name, age) {//new function () uniqueness
this.name = name;
This.age = age;
This.run = new Function ("return this.name + this.age + ' run ... ');
}

We can bind the same function outside of the constructor to ensure the consistency of the reference address, but this practice is not necessary, but to deepen learning to understand:

function Box (name, age) {
this.name = name;
This.age = age;
This.run = run;
function run () {//through the outside call, to ensure that the reference address consistent return
THIS.name + this.age + ' running ... ';
}

While using the global function run () to solve the problem of ensuring a consistent reference address, this approach brings up a new problem, which, when called by the object, is the Box itself, and as a normal function call, this also represents window.

Every function we create has a prototype (prototype) attribute, which is an object that contains properties and methods that can be shared by all instances of a particular type.

Logically you can understand this: the prototype object of the object that prototype created by calling the constructor. The benefits of using prototypes allow all object instances to share the properties and methods that it contains. That is, you do not have to define object information in the constructor, but you can add that information directly to the prototype.

function Box () {}//declares a constructor
Box.prototype.name = ' Lee ';
Box.prototype.age = m;
Box.prototype.run = function () {return
this.name + this.age + ' run ... ';

Compare the method addresses within the prototype to be consistent:

var box1 = new Box (); Add a property to the prototype//Add a method to the prototype
var box2 = new Box ();
Alert (Box1.run = = Box2.run); True, the method's reference address remains consistent

In the prototype schema declaration, there are two more attributes, both of which are generated automatically when the object is created. The __proto__ property is a pointer to a prototype object that is directed to a stereotype property of a constructor constructor. With these two properties, you can access the properties and methods in the prototype. Ps:ie browsers can not be identified in the script access __proto__, Firefox and Google browsers and some other browsers are recognizable. Although it can be exported, internal information cannot be obtained.

alert (box1.__proto__);//[object Object]

To determine whether an object points to a prototype object for the constructor, you can use the isPrototypeOf () method to test it.

Alert (Box.prototype.isPrototypeOf (Box));

Whenever an object is instantiated, it points to the execution flow of the prototype pattern:

1. First find the property or method in the constructor instance, if there is, return immediately;

2. If there is no constructor instance, go to its prototype object and, if so, return it; Although we can access values stored in the prototype through an object instance, we cannot access the values in the prototype by overriding the object instance.

var box1 = new Box (); alert (box1.name);//lee, the value in the prototype
box1.name = ' Jack '; alert (box.1name);//jack, proximity principle,
var box2 = new box (); Alert ( Box2.name); Lee, the value in the prototype was not modified by Box1.

If you want to Box1 can also continue to access the value of the prototype in the back, you can delete the properties in the constructor, specifically as follows:

Delete box1.name;//Deletes the attribute alert (box1.name);

How to determine whether 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 '));//Instance returns TRUE, otherwise returns false

Constructor instance properties and prototype properties, the in operator returns true if the given property is accessible through an object, whether the property exists in the instance or in the prototype.

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.