The prototype property of the JavaScript constructor

Source: Internet
Author: User
Tags instance method uppercase letter

There is no concept of class in JavaScript, so it differs from object-oriented language in object creation.

The object in JS can be defined as a collection of unordered attributes. Its properties can contain basic values, objects, and functions. An object is essentially a set of values that have no particular order, and each property and method in the object has a name, each of which is mapped to a value, so we can think of the object as a hash table.

JS is an object-based language, the concept of objects in the JS system is very important, so it is necessary to clearly understand the JS in the common methods of object creation and their respective limitations.

    • Use Object or object literal creates objects
    • Factory mode Creation Object
    • Constructor mode Create object
    • Prototype schema creation Object
    • Constructing and prototyping blending modes creating objects
To create an object using object or literal literals

before we talk about Factory mode creating objects, we might recall JS in the most basic method of creating objects, such as I want to create a student object to do? Most simply, new is an object:

var student = new Object ();

Student.name = "Easy";

Student.age = "20";

in this way, a student object is created with 2 properties name and age, each assigned to "easy" and 20.

If you suspect that this approach has a feeling of poor encapsulation, we can also create student objects using object literals :

var sutdent = {

Name: "Easy",

Age:20

};

It seems to be perfect. But right away we will find a very sharp question: when we want to create the same kind of student1,student2,...,studentn, we have to repeat the above code n times.

var sutdent1 = {

Name: "Easy1",

Age:20

};

var Sutdent2 = {

Name: "Easy2",

Age:20

};

...

var sutdentn = {

Name: "Easyn",

Age:20

};

can it be like a factory floor where a lathe is constantly producing objects? We look at "Factory mode".

Factory mode Creation Object

JS does not have the concept of class, then we might as well use a function to encapsulate the above object creation process to facilitate repeated calls, and can give a specific interface to initialize the object:

function createstudent (name, age) {

var obj = new Object ();

Obj.name = name;

Obj.age = age;

return obj;

}

var student1 = createstudent ("easy1", 20);

var student2 = createstudent ("Easy2", 20);

...

var studentn = createstudent ("Easyn", 20);

This allows us to continuously "produce" objects through the Createstudent function. It seems that there is peace of mind, but greedy humans have a nature that is not content with the status quo: we not only want the production of "products" to be as constant as the factory floor, we also want to know what kind of product is produced.

For example, we also define the Createfruit () function of the "produce" fruit object:

function createfruit (name, color) {

var obj = new Object ();

Obj.name = name;

Obj.color = color;

return obj;

}

var v1 = createstudent ("easy1", 20);

var v2 = createfruit ("Apple", "green");

for the above code created objects V1, v2, we use the instanceof operator to detect, they are all object type. Of course we are not satisfied with this, we want V1 to be student type, and V2 is the fruit type. To achieve this goal, we can create objects using the method of a custom constructor.

constructor mode Create object

Create on top When we use primitive objects such as object, we have used their constructors:

var obj = new Object ();// This creates a native object

when creating a native array An array type object is also used with its constructor:

var arr = new Array (10); Constructs an array object with an initial length of 10

Before creating an object with a custom constructor, let's first look at what the difference between a constructor and a normal function is.

First , there is actually no special syntax for creating constructors, and the only difference from a normal function is the invocation of a method. For any function that is called with the new operator, it is a constructor and is not called with the new operator, so it is a normal function.

second, by convention, we agree that the constructor name begins with an uppercase letter, and the normal function starts with a lowercase letter, which facilitates the explicit distinction between the two. For example, the new Array () above, new Object ().

Thirdly, when the constructor is called using the new operator, it goes through (1) Creating a new object, (2) assigning the constructor scope to the new object (which points to the new object), (3) Executing the constructor code, (4) Returning the new object, and 4 stages.

After understanding the differences between constructors and normal functions, we use constructors to rewrite the factory-mode functions and add a method property:

function Student (name, age) {// = equivalent to Java constructor, but no class concept

THIS.name = name;

This.age = age;

This.alertname = function () {

Alert (this.name)

};

}

function Fruit (name, color) {

THIS.name = name;

This.color = color;

This.alertname = function () {

Alert (this.name)

};

}

so we can create separate Objects for student and fruit:

var v1 = new Student ("Easy", 20);

var v2 = new Fruit ("Apple", "green");

Then we can use the instanceof operator to detect the above object type to distinguish between student and fruit:

Alert (v1 instanceof Student); True

Alert (v2 instanceof Student); False

Alert (v1 instanceof Fruit); False

Alert (v2 instanceof Fruit); True

Alert (v1 instanceof Object); True any object is inherited from Object

Alert (v2 instanceof Object); True any object is inherited from Object

This solves the embarrassment that the Factory mode cannot differentiate between object types. Is it perfect to use construction methods to create objects?

we know that in In JS, a function is an object. So, when we instantiate more than one student object:

var v1 = new Student ("Easy1", 20);

var v2 = new Student ("Easy2", 20);

...

var vn = new Student ("Easyn", 20);

The common alertname () function is also instantiated n times, because different student objects do not share the Alertname () function, and we can use the following methods to detect different The student object does not share the Alertname () function:

Alert (V1.alertname = = V2.alertname); Flase, because this is pointing to two different Student Objects

we know thatthe This object is bound at run time based on the execution environment of the function. In the global function, the This object is equal to window, and in the object method, this points to the object. In the constructor above:

This.alertname = function () {

Alert (this.name)

};

When we create an object (before executing the Alertname function), we bind the Alertname () function to the object. We can do this again when we execute the function, by moving the object method outside the constructor:

function Student (name, age) {

THIS.name = name;

This.age = age;

This.alertname = Alertname;

}

function Alertname () {

alert (this.name);

}

var stu1 = new Student ("Easy1", 20);

var stu2 = new Student ("Easy2", 20);

When Stu1.alertname () is called , the This object is bound to STU1, and the This object is equal to window when there is no call.

We define the Alertname () function as a global function so that the Alertname property in the object is set to a pointer to that global function. This global function is shared by STU1 and STU2, which solves the problem of memory wasting.

However, it is not a good solution to solve the problem of sharing internal objects through the way of global functions. If there are many global functions defined in this way, we want to encapsulate the custom objects almost impossible to achieve. A better solution is to use the prototype object pattern.

prototype schema creation object
    • Prototype objects for functions
    • Association of object instances and prototype objects
    • Creating objects using a prototype model
    • Limitations of prototype model creation objects
prototype objects for functions

Before you know how to create objects using the prototype schema, it is necessary to figure out what a prototype object is.

Each function we create has a prototype property, which is a pointer to an object. For the constructor we created, the object contains properties and methods that can be shared by all instances. As shown below:

function.prototype===function.__proto__//result is True

Object.prototype a prototype object that points to the object constructor, and some of the properties and methods in the prototype object are shared by all instances, that is, global properties and methods, such as ToString (), ValueOf ()

Array.prototype a prototype object that points to an array constructor, as above there are attribute methods that have an instance commonality. That is, common array methods and properties.

String.prototype and so on are all the same.

This property is added by default when we use the JS system or the object we create. any object has a constructor property, inherits from the prototype, andconstructor points to the constructor or constructor that constructs the object.

Constructor can be rewritten, so use caution.

By default, all prototype objects automatically contain a constructor property , which is also a pointer to the function where prototype is located:

Each object has a constructor property that points to the constructor of the object.

In JavaScript, because a function is also an object, the constructor is also an object. A constructor is an instance of a function. So the constructor of the constructor object points to the constructor of the constructor object, which is the function. All function constructors are functions, and all functions are an instance object of function

Function.constructor===function

Object.constructor===function

Array.constructor===function string.constructor===function

Association of object instances and prototype objects

when the constructor is called to create a new instance, the interior of the instance automatically contains a [[Prototype]] pointer property, which refers to the prototype object that points to the constructor. Note that this pointer is associated with the instance and constructor of the prototype object instead of the instance and constructor:

in JavaScript , the constructor property returns the constructor for an object.

The return value is a reference to a function, not a function name:

JavaScript Array constructor property returns function Array () {[native code]}

JavaScript Number constructor property returns function number () {[native code]}

JavaScript String constructor property returns returns function string () {[native code]}

var fruits = ["Banana", "Orange", "Apple", "Mango"];

var ary=fruits.constructor;

alert (ary);// popup function Array () {[native code]}

alert (fruits.constructor===ary);// popup true

alert (fruits.constructor===array);// popup true

Therefore:student.prototype.constructor===student

creating objects using a prototype model adding properties and methods directly to the prototype object

After understanding the prototype object, we can implement the sharing of data between objects by adding properties and methods to the constructor prototype object. For example:

function Student () {

}

Student.prototype.name = "Easy";

Student.prototype.age = 20;

Student.prototype.alertName = function () {

alert (this.name);

};

var stu1 = new Student ();

var stu2 = new Student ();

Stu1.alertname (); Easy

Stu2.alertname (); Easy

Alert (Stu1.alertname = = Stu2.alertname); True both share the same function

The above code, we are in The name, age property, and Alertname () method are added to the student Protptype object. However, the STU1 and STU2 created do not contain the name, the age property, and the Alertname () method, and contain only one [[prototype]] pointer property. When we call Stu1.name or Stu1.alertname (), how do we find the corresponding properties and methods?

When we need to read a property of an object, we perform a search. The property is first looked up in the object, and if found, returns the property value; otherwise, the lookup continues to the prototype object that [[prototype]] points to.

From This we can also see another layer of meaning: If an object instance contains a property or method with the same name in the prototype object, the same Name property or method in the object instance masks the same Name property or method in the prototype object. The reason is "First look up the property in the object, and if found, return the property value;"

Owning an instance property or method of the same name:

, we will get "Easysir" when we visit Stu1.name:

alert (stu1.name); Easysir

overriding a prototype object by object literal

many times, we use object literals to directly rewrite the entire prototype object for ease of writing and intuitive "encapsulation":

function Student () {

}

Student.prototype = {

Constructor:student,

Name: "Easy",

AGE:20,

Alertname:function () {

alert (this.name);

}

};

It is important to note that we are using the object literal to recreate a Object, and then student the prototype pointer to the object. During the creation of the object, the new constructor property is automatically obtained, which points to the constructor of object. Therefore, in the above code, we added constructor:student to re-refer to the Student constructor.

limitations of prototype model creation objects

The prototype model gives us great convenience in sharing data with object instances, but often different instances will want to have their own individual attributes. We use both the constructor model and the prototype model for both data sharing and "no sharing."

constructing and prototyping blending modes creating objects

We use the following methods to create an object, combining the advantages of the prototype pattern in shared method properties and the constructor pattern in instance method properties:

We want each Stu to have its own name and age property

function Student (name, age) {

THIS.name = name;

This.age = age;

}

All Stu should share a alertname () method

Student.prototype = {

Constructor:student,

Alertname:function () {

alert (this.name);

}

}

var stu1 = new Student ("Jim", 20);

var stu2 = new Student ("Tom", 21);

Stu1.alertname (); Jim Instance Properties

Stu2.alertname (); Tom Instance Properties

Alert (Stu1.alertname = = Stu2.alertname); True shared functions

Above, defining the instance properties in the constructor, defining the pattern of shared properties in the prototype, is the most widely used method. Typically, we will use this method to define reference type variables by default.

The prototype property of the JavaScript constructor

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.