The prototype and object mechanism in JavaScript

Source: Internet
Author: User

1 Some language features related to objects

1.1 Everything is an object
Everything in JavaScript is an object. An object is a collection of properties. Primitive values, such as numbers, strings, and Booleans, are "pseudo-objects", which also have properties, but are allocated on the stack and passed by value. Other objects are allocated on the heap and passed by reference.
A very important concept is that a function is also an object that can be used as the value of a variable, return a value, a parameter, or a value of a property. A special place for function objects is the ability to execute code contained within the XXX function object through the "xxx ()" syntax. Because of this particularity, typeof xxx will return function, but this is only a convenience facility.

1.2 Properties of an object can be added and deleted dynamically

var foo = new Object ();
Add Bar property to Foo object
Foo.bar = "Foobar";
alert (foo.bar); Foobar
Delete Foo object's Bar Property
Delete Foo.bar;
alert (foo.bar); Undefined


1.3 Except for host objects, all other objects are created by constructors
To have an object, you first need to have a method for creating the object.
In C++/java and other languages, this method is to instantiate XXX class an instance of XXX.
In the JavaScript world there is no real class, and of course, idioms like "class" and "instance" can be used to describe similar behavior in JavaScript, but the mechanism is completely different. JavaScript objects are created by constructors, and each object has a constructor property that represents the constructor that created the object:

function Test () {this.a = "Hello";}
var test = new Test (); Created by the test constructor
alert (test.constructor);

var o = {A: "Hello"};
actually equivalent to
var o_ = new Object ();
o_.a = "Hello"; Created by the object constructor
alert (o.constructor);

The constructor is also an object, and what is the constructor created from? Built-in function functions:

function Test (A, B)
{
alert (A+B);
}
Equivalent:
Test = new Function (["A", "B"], "alert (a+b);");

What are function functions created by? The function is actually an intrinsic object of native code implementation. However, for consistency, the function also has the constructor property, which points to itself. Connect to the code above:

/* Output function function () {
[Native code]
}
*/
alert (test.constructor);

Alert (Test.constructor.constructor = = = Test.constructor); True
Alert (Test.constructor = = = Object.constructor); True


2 prototype prototype
The concept of 2.1 prototype
Prototype is a property of a constructor that points to an object. This object will act as the base reference for all instances created by the constructor (base reference), and you can think of the object's base reference as an automatically created hidden property. When a property of an object is accessed, the object itself is first found and then returned; If not, look for the properties of the object that the base reference points to (if you still can't find it, you'll actually find it up along the prototype chain until you get to the root). As long as it is not overwritten, the properties of the object prototype can be found in all instances.
The prototype defaults to a new instance of object, and because it is still an object, you can add a new property to the object:

Prototype defaults to new Object (); For convenience, remember as P_obj
function person (name) {
THIS.name = name;
}

Add Sayname property for P_obj
Person.prototype.sayName = function () {
alert (this.name);
}

var john = new Person ("John"); John's base reference points to P_obj
var Eric = new Person ("Eric"); Eric's base reference also points to p_obj

Note the This in the Sayname code points to the instantiated object (this binding)
John.sayname (); The John object itself does not have a Sayname property, so access to the Sayname property of the prototype object P_obj
Eric.sayname (); Accessing the Sayname property of the same prototype object P_obj


var tmp = Person.prototype;
Tmp.boss = "David";
At this point of operation, P_obj has been modified
Based on the above attribute access process, new modifications (Boss properties) can be reflected in all instances, including those created and about to be created
Alert ("John ' s boss is" + John.boss);
Alert ("Eric ' s boss is" + Eric.boss);


The Hiscar and Saycar properties are added to the John object instead of the P_obj object:
John.hiscar = "Audi";
John.saycar = function () {
Alert (THIS.name + "has a car of" + This.hiscar);
}
John.saycar ();
// .. So the next sentence will be wrong because the Eric object itself and the prototype P_obj have no sayname properties
/* Eric.saycar (); */


2.2 Prototype chain
In addition to modifying the object that prototype points to, you can also modify which object the prototype points to, which is to give prototype a different object. This allows for a simple inheritance:

function Superman () {}
Superman.prototype.sayHello = function () {
Alert ("I ' m a Superman.");
}

function Supermancan (skill) {
This.skill = skill;
}
An instance of Superman is given to prototype.
Supermancan.prototype = new Superman ();
// .. To add new properties dynamically
SupermanCan.prototype.sayMore = function () {
This.sayhello (); Methods that call the "parent class"
Alert ("I can" + This.skill);
}

var david = new Supermancan ("Fly");
Output:i ' m a Superman. I can Fly
David.saymore ();

If you instantiate an object first, and then assign a different object to the constructor prototype, the base reference for the object you have created will be the same, and the base reference for the object you are creating will be the new prototype object:

var f1 = {echo:function () {alert ("Sound");}};
function Foo () {};
var foo = new Foo (); The base reference of Foo points to an object instance
Foo.prototype = F1;
/* Undefined because this is the "Foo object itself or the object pointed to by the base reference has the Echo property?"
Instead of the "Foo object itself or the object pointed to by Foo.prototype has the Echo property?" */
alert (Foo.echo);

var foo2 = new Foo (); Foo2 base reference refers to F1 object
Foo2.echo (); Output:sound

The prototype of all constructors cannot be null, meaning Superman.prototype = null is ignored by the interpretation engine; On the other hand, the object constructor also has the prototype property (which is read-only, can add attributes to the prototype but cannot be assigned to different objects), so it can have multiple layers of prototype chain, but the root of the prototype chain must be object.prototype. This means that adding a property to Object.prototype affects all objects:

Object.prototype.echo = function () {
Alert ("Hello");
}

The Echo property is added to all object-native objects and custom objects

var arr = new Array ();
Arr.echo ();
Array.echo ();

function Objcons () {
This.dummy = "D";
}
var obj = new Objcons ();
Obj.echo ();
Objcons.echo ();


3. The essence of constructors and new
A constructor is an out-of-the-fact function that a function can become a constructor because of the new operator:

this.msg = "Window";

function Test ()
{
alert (this.msg);
}

Test (); Window
var test = new Test (); Undefined. Because the test object does not have a MSG attribute defined

The difference is in how to cut into the object: Test () executes the code in the context of an object (window in the example), that is, this object is pointed to; New Test () creates an object and executes the code with the new object as the context (this points to the new object), and then returns the new object.
If there is a function:

function Test () {
var dummy = "has money";
This.wish = dummy;
DoSomething ();

}

In combination with all of the above, it can be inferred that the pseudo-code of the new Test () behavior is:
Create a new object temp;
Temp.constructor = Test;
Temp. (base reference) = Test.prototype; This sentence is executed before the code body, meaning that the this.xxx in the constructor can access the properties of the prototype object xxx
Bind:this = temp; Binds this to the Temp object
Start executing function code
var dummy = "has money";
This.wish = dummy; Add the Wish property to the Temp object
DoSomething ();
....
End Execution Function code
return temp;
This does not necessarily conform to the internal binary implementation, but it does a good job of explaining the features of JavaScript.

The prototype and object mechanism in JavaScript

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.