JavaScript Object-oriented and prototype (i): constructors

Source: Internet
Author: User

Referring to constructors, we are not unfamiliar, in the object-oriented domain, the constructor is already a commonplace problem. Learning again in JavaScript really has a kind feeling.

one, simple review            

             Constructor, is a special method. Used primarily to initialize objects when they are created, that is, object member variable Assign initial value, total with new operator use in the statement that created the object , they can be differentiated by their number of arguments or by the different types of arguments overloaded.


C # Constructor (a simple small example):

<span style= "FONT-SIZE:14PX;" >public class Cat () {private string Name= "";p ublic Cat ()                          //without parameters, if there is no custom constructor, this is the default {                this.name= "anonymous";} Public Cat (string name)   //constructor defined, with parameter {this.name=name;}} </span>

Since constructors are used when creating functions, How do you create functions in JavaScript?

Second, JavaScript Creating Objects

1 , direct use New to create an object, look directly at the following code:

<span style= "FONT-SIZE:14PX;" >var box = new Object (); Create an object box.name = ' JavaScript '; Create a Name property and assign a value of box.runtime = 100; Create an Age property and assign a value of Box.run = function () {//Create a run () method and return a value     of return this.name + This.runtime + ' running ... ';}; Alert (Box.run ()); The value of the output properties and methods </span><span style= "FONT-SIZE:18PX;" ></span>

There is a problem, when you want to create a similar class, there will be a lot of duplicate code. In order to resolve multiple object-like claims, you can use Factory mode. Here you can recall the factory in design mode, that is, to solve the problem of how to instantiate the object.

<span style= "FONT-SIZE:14PX;" >function CreateObject (name, age) {//function of the set instantiation      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); The first instance of var Box2 = CreateObject (' Jack ', 200); The second instance is alert (Box1.run ()); alert (Box2.run ()); Stay independent </span>

Second, the construction function to play:

Factory mode is used to solve the problem of a large number of repetitions of instantiated objects. But it's impossible to figure out exactly which object they are, that is, to identify the problem. This leads to the constructor function.

Constructors (construction methods) can be used in ECMAScript to create specific objects. The type is in object.

<span style= "FONT-SIZE:14PX;" >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 ', 100); New box () can be var box2 = new Box (' Jack ', ';</span> ')

The constructor and Factory mode methods differ in the following ways:

1. The constructor method does not display the created object (NewObject ());

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

3. There is no Renturn statement.

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.

New Object () executes the following procedure:

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 created by new object), and this in the function body

Represents the object that is a new object ().

3. Execute the code within the constructor;

4. Returns the new object (returned directly from the background).


(iii) Determine whether the method inside the constructor is a basic type or a reference type

use the above constructor Box () , make the following comparisons:

<span style= "FONT-SIZE:14PX;" >var box1 = new Box (' Lee ', 100); Pass consistent var box2 = new Box (' Lee ', 100); IBID. alert (Box1.name = = Box2.name); True, the value of the property is equal to alert (box1.run () = = Box2.run ()); True, the value of the method is equal because the argument is consistent with alert (Box1.run = = Box2.run); False, the method is actually a reference address </span>

their addresses are different after instantiating box1 and box2 , although the value of the run () method is the same, But it returns false when comparing the reference addresses of their methods . This proves that the method inside the constructor is a reference type.

To guarantee the consistency of the reference address, you can bind a method outside the constructor to the same function.

function Box (name, age) {      this.name = name;<pre name= "code" class= "JavaScript" >      <span style= " Font-family: the song body; >this.age = age;</span>
This.run = run;} function run () {//via outside call, ensure reference address consistent return THIS.name + this.age + ' running ... ';}

Although the global function run () is used to solve the problem of ensuring that the reference address is consistent, this approach introduces a new problem, in which the this is the box itself when the object is called, and it is called as a normal function. Time,Thisalso represents window. This leads to an indefinite problem with this.

Problems continue to arise, and we always have the means to solve, this is the wisdom of mankind ... See Small series Analysis prototypes






JavaScript Object-oriented and prototype (i): constructors

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.