Structure object

Well, take us to discuss the creation of the object to another method.

In addition to JSON, in JavaScript, we can use the new operator of the form combined with a function to create objects. For example:

Js code

  1. function MyFunc () (); / / define an empty function
  2. r anObj = new MyFunc (); / / use the new operator, with MyFun function, on the creation of an object

      function MyFunc() {};         //定义一个空函数
    var anObj = new MyFunc();  //使用new操作符,借助MyFun函数,就创建了一个对象

JavaScript to create objects of this can be really interesting to understand how such a manner?

In fact, you can put the above code rewritten into the equivalent of such forms:

Js code

  1. function MyFunc (){};
  2. var anObj = (); / / create an object
  3. MyFunc.call (anObj); / / will anObj object as this function pointer to call myFunc

      function MyFunc(){};
      var anObj = {};     //创建一个对象
    MyFunc.call(anObj); //将anObj对象作为this指针调用MyFunc函数

We can interpret it this way, JavaScript first new operator to create an object, this object will be followed by this parameter as a function of call behind. In fact, JavaScript is done within, and any function can be called such! However, "anObj = new MyFunc ()" in this form, we can also see a familiar figure, C + + and C # do not create the object is it? It turned out that All roads lead to Lingshan, achieving the same ah!

Jun seen here may think, why should we not put this myFunc it as a constructor? Congratulations, the correct answers! JavaScript is also a thought! See the following code:

Java code

  1. function Person (name) / / constructor with parameters
  2. (
  3. this. name = name; / / will give the parameter values assigned to this object property
  4. this. SayHello = function () (alert ( "Hello, I'm" + this. name);); / / give this object to define a method SayHello.
  5. );
  6. function Employee (name, salary) / / sub-constructor
  7. (
  8. Person.call (this, name); / / will this pass the parent constructor
  9. this. salary = salary; / / set up a salary of this property
  10. this. ShowMeTheMoney = function () (alert (this. name + "$" + this. salary);); / / add ShowMeTheMoney Ways.
  11. );
  12. var BillGates = new Person ( "Bill Gates"); / / constructor used to create Person object BillGates
  13. var SteveJobs = new Employee ( "Steve Jobs", 1234); / / constructor used to create Empolyee object SteveJobs
  14. BillGates.SayHello (); / / show: I'm Bill Gates
  15. SteveJobs.SayHello (); / / show: I'm Steve Jobs
  16. SteveJobs.ShowMeTheMoney (); / / show: Steve Jobs $ 1234
  17. alert (BillGates.constructor == Person); / / show: true
  18. alert (SteveJobs.constructor == Employee); / / show: true
  19. alert (BillGates.SayHello == SteveJobs.SayHello); / / show: false

function Person(name)   //带参数的构造函数
{
      this.name = name;   //将参数值赋给给this对象的属性
    this.SayHello = function() {alert("Hello, I'm " + this.name);};   //给this对象定义一个SayHello方法。
};
function Employee(name, salary)     //子构造函数
{
      Person.call(this, name);        //将this传给父构造函数
    this.salary = salary;       //设置一个this的salary属性
    this.ShowMeTheMoney = function() {alert(this.name + " $" + this.salary);};  //添加ShowMeTheMoney方法。
};
   
var BillGates = new Person("Bill Gates");   //用Person构造函数创建BillGates对象
var SteveJobs = new Employee("Steve Jobs", 1234);   //用Empolyee构造函数创建SteveJobs对象

BillGates.SayHello();   //显示:I'm Bill Gates
SteveJobs.SayHello();   //显示:I'm Steve Jobs
SteveJobs.ShowMeTheMoney();   //显示:Steve Jobs $1234

alert(BillGates.constructor == Person);  //显示:true
alert(SteveJobs.constructor == Employee);  //显示:true
 
alert(BillGates.SayHello == SteveJobs.SayHello); //显示:false

This code shows that not only can function as a constructor, but also can take parameters, can also add members and methods of the object. One of the first 9 lines, Employee constructor will receive its own as a parameter of this call Person constructor, which is equivalent to call the base class's constructor. 21,22 also show that the first line of such a meaning: BillGates are constructed by the Person, and SteveJobs are constructed by the Employee. Built-in object constructor property is also specified in the object structure used in the specific function!

In fact, if you are willing to function as a "category", she is the "category", because she already has "Class" of those characteristics. Is not it? Give birth to her son all have the same characteristics, but also with the type constructor of the same name it!

Yet it must be noted, the operation of this object constructor to create an object out of each, not only with members of their respective data, but also has its own method of data. In other words, the method code body (embodiment of the logic function of data) at each object in a copy of all existence. Although a copy of each of the logic of the code are the same, but the objects were indeed a code to preserve their own body. Example on the last sentence of the facts shows, this also explains the JavaScript function is the object of the concept.

The same type of object has a method of their code is a waste. In a traditional programming language, the method does not function as JavaScript object as a concept. Even if there are like function pointers, method pointer, or as changes in the form of commission, but its essence is to invoke the same code. The target language in general difficult to come across such cases.

However, JavaScript language has great flexibility. We can only approach the definition of a function body, and this object structure to use the only function of the object as part of its methods, will be able to share the method logic. For example:

Java code

  1. function SayHello () / / first define a function code SayHello
  2. (
  3. alert ( "Hello, I'm" + this. name);
  4. );
  5. function Person (name) / / constructor with parameters
  6. (
  7. this. name = name; / / will give the parameter values assigned to this object property
  8. this. SayHello = SayHello; / / give this object SayHello Ways SayHello that assignment for the previous code.
  9. );
  10. var BillGates = new Person ( "Bill Gates"); / / create object BillGates
  11. var SteveJobs = new Person ( "Steve Jobs"); / / create object SteveJobs
  12. alert (BillGates.SayHello == SteveJobs.SayHello); / / show: true

function SayHello()     //先定义一份SayHello函数代码
{
    alert("Hello, I'm " + this.name);
};
    
function Person(name)   //带参数的构造函数
{
        this.name = name;   //将参数值赋给给this对象的属性
     this.SayHello = SayHello;   //给this对象SayHello方法赋值为前面那份SayHello代码。
};

    var BillGates = new Person("Bill Gates");   //创建BillGates对象
    var SteveJobs = new Person("Steve Jobs");   //创建SteveJobs对象
    
    alert(BillGates.SayHello == SteveJobs.SayHello); //显示:true

Among them, the last line of the output results show that the two objects is indeed a shared function objects. Although this process has reached a method of sharing the purpose of the code, but not very elegant. Since the definition SayHello methods do not reflect its relationship with the Person class. "Elegant," the term used to describe the code, do not know who are put forward. However, the word reflects the programmers code from the pursuit of the correct, efficient, reliable and easy to read on a reciprocal basis, toward the pursuit of beautiful code realm of feeling and artistic level of development, the program also Any additional romantic life.

Clearly, JavaScript morning thought of this question, her designers to provide a fun concept prototype.

Watch the early prototype

prototype derived from the French, the software sector standards translated as "prototype", the representative of the initial shape of things, but also contain models and model significance. JavaScript concept of prototype appropriately reflects the content of the word, we should not be interpreted as a C + + pre-statement of the kind of prototype concept.

JavaScript all the function types of objects have a prototype property. The prototype property itself is a type of object, so we can also give the prototype object to add arbitrary attributes and methods. Now that prototype object are the "prototype", then the function should be constructed out of objects will have this "prototype" features. In fact, in the constructor's prototype on the definition of all properties and methods, can be constructed through the object of direct visits and calls. Can also say, prototype object to provide a group of similar properties and methods of sharing mechanisms.

Let us take a look the following code:

Js code

  1. function Person (name)
  2. (
  3. this. name = name; / / set object properties, each object a property of their respective data
  4. );
  5. Person.prototype.SayHello = function () / / function prototype give Person Ways SayHello add.
  6. (
  7. alert ( "Hello, I'm" + this. name);
  8. )
  9. var BillGates = new Person ( "Bill Gates"); / / create object BillGates
  10. var SteveJobs = new Person ( "Steve Jobs"); / / create object SteveJobs
  11. BillGates.SayHello (); / / object through direct calls to BillGates Ways SayHello
  12. SteveJobs.SayHello (); / / through a direct call to the object SteveJobs Ways SayHello
  13. alert (BillGates.SayHello == SteveJobs.SayHello); / / Since the two objects are shared prototype of SayHello, so show: true

function Person(name)
    {
        this.name = name;   //设置对象属性,每个对象各自一份属性数据
    };
    
    Person.prototype.SayHello = function()  //给Person函数的prototype添加SayHello方法。
    {
        alert("Hello, I'm " + this.name);
    }

    var BillGates = new Person("Bill Gates");   //创建BillGates对象
    var SteveJobs = new Person("Steve Jobs");   //创建SteveJobs对象

    BillGates.SayHello();   //通过BillGates对象直接调用到SayHello方法
    SteveJobs.SayHello();   //通过SteveJobs对象直接调用到SayHello方法

    alert(BillGates.SayHello == SteveJobs.SayHello); //因为两个对象是共享prototype的SayHello,所以显示:true

Program showed that the prototype constructor method on the definition of the object could indeed be a direct call through to, and code are shared. Clearly, the methods set to prototype formulation seems more elegant, although the call has not changed form, but it reflects on the logic of methods and types of relations, the relative in front of the wording easier to understand and organize code.

Then, for multi-level type constructor situation be?

We will look at the following code:

Js code

  1. function Person (name) / / base class constructor
  2. (
  3. this. name = name;
  4. );
  5. Person.prototype.SayHello = function () / / to base class constructor's prototype add method
  6. (
  7. alert ( "Hello, I'm" + this. name);
  8. );
  9. function Employee (name, salary) / / subclass constructor
  10. (
  11. Person.call (this, name); / / Call base class constructor
  12. this. salary = salary;
  13. );
  14. Employee.prototype = new Person (); / / build a base class object as a subclass prototype prototype here is very interesting
  15. Employee.prototype.ShowMeTheMoney = function () / / to subclass constructor prototype Tim Add method
  16. (
  17. alert (this. name + "$" + this. salary);
  18. );
  19. var BillGates = new Person ( "Bill Gates"); / / create a base class of the Person object BillGates
  20. var SteveJobs = new Employee ( "Steve Jobs", 1234); / / create a subclass of the Employee object SteveJobs
  21. BillGates.SayHello (); / / through a direct call to the prototype object of the Ways
  22. SteveJobs.SayHello (); / / through the sub-class object directly call the base class method prototype concern!
  23. SteveJobs.ShowMeTheMoney (); / / the object directly through the sub-class called subclass prototype method
  24. alert (BillGates.SayHello == SteveJobs.SayHello); / / show: true, show that the prototype approach is shared

         function Person(name)   //基类构造函数
    {
         this.name = name;
     };
    
     Person.prototype.SayHello = function()  //给基类构造函数的prototype添加方法
     {
         alert("Hello, I'm " + this.name);
     };
     
     function Employee(name, salary) //子类构造函数
    {
         Person.call(this, name);    //调用基类构造函数
         this.salary = salary;
};

Employee.prototype = new Person();  //建一个基类的对象作为子类原型的原型,这里很有意思

Employee.prototype.ShowMeTheMoney = function()  //给子类添构造函数的prototype添加方法
{
alert(this.name + " $" + this.salary);
};

var BillGates = new Person("Bill Gates");   //创建基类Person的BillGates对象
var SteveJobs = new Employee("Steve Jobs", 1234);   //创建子类Employee的SteveJobs对象

BillGates.SayHello();       //通过对象直接调用到prototype的方法
SteveJobs.SayHello();       //通过子类对象直接调用基类prototype的方法,关注!
SteveJobs.ShowMeTheMoney(); //通过子类对象直接调用子类prototype的方法

alert(BillGates.SayHello == SteveJobs.SayHello); //显示:true,表明prototype的方法是共享的

Section 17 of this code line, construction of a base class object and set the subclass constructor prototype, this is very interesting. The purpose of this is that for the first 28 lines, through the sub-class object can also directly call the base class method prototype. Why is it so?

In fact, in the JavaScript in, prototype objects can not only share their wealth, and the prototype was also寻根问祖nature, allowing the legacy of our ancestors can be passed from generation to generation. When reading from an object where the property or call the method, the object itself if there is no such property or method, it will go its own associated prototype object, where looking for; prototype if not, will go their associated prototype, where the older generation prototype search until you find or trace the process until the end.

JavaScript at the internal, object properties and methods of retrospective mechanism is through the so-called prototype chain to achieve. When using new operator object structure will also be the object constructor prototype is assigned to the newly created object, become the targets of the built-in object prototype. Built a prototype object is the external object is not visible, although some browsers (such as Firefox) can allow us to access the built prototype, but do not propose to do so. Built a prototype object is itself the object, also has its own associated prototype object, thus forming the so-called prototype chain.

At the end of the prototype chain is the Object constructor prototype property that point to a prototype object. The prototype objects are all objects of the oldest ancestors, the ancestors, such as the toString implementation, such as all objects have a natural on the way. Other built-in constructor function, such as Function, Boolean, String, Date and RegExp, such as the prototype are inherited from the ancestors, but also defined their own properties and methods, so their children and grandchildren on the performance of their respective clans those characteristics.

Is not that what "inheritance" do? Yes, this is the "inheritance", are unique to JavaScript "prototype inheritance."

"Prototype inheritance" is a kind and severe. Prototype object to their property and means to contribute selflessly to the children to use, but also do not force children to be complied with, permit a number of naughty children by their own interests and hobbies to act independently. From this point of view, the prototype object is a kind-hearted mother. However, any one child can go its own way, but it should not move the prototype object existing property, because it may affect the interests of other children. From this point of view, the prototype object also as a strict father. We take a look at the following code can be understood that way:

Js code

  1. function Person (name)
  2. (
  3. this. name = name;
  4. );
  5. Person.prototype.company = "Microsoft"; / / prototype property
  6. Person.prototype.SayHello = function () / / prototype of the Ways
  7. (
  8. alert ( "Hello, I'm" + this. name + "of" + this. company);
  9. );
  10. var BillGates = new Person ( "Bill Gates");
  11. BillGates.SayHello (); / / because of inherited prototype things honest output: Hello, I'm Bill Gates
  12. var SteveJobs = new Person ( "Steve Jobs");
  13. SteveJobs.company = "Apple"; / / set up your own company property to cover up the prototype property of the company
  14. SteveJobs.SayHello = function () / / implementation methods SayHello their own to cover up the prototype SayHello Ways
  15. (
  16. alert ( "Hi," + this. name + "like" + this. company + ", ha ha ha");
  17. );
  18. SteveJobs.SayHello (); / / are covered by their own properties and methods, output: Hi, Steve Jobs like Apple, ha ha ha
  19. BillGates.SayHello (); / / SteveJobs coverage does not affect the prototype object, BillGates old way or the output

 function Person(name)
    {
        this.name = name;
    };
    
    Person.prototype.company = "Microsoft"; //原型的属性
    
    Person.prototype.SayHello = function()  //原型的方法
    {
        alert("Hello, I'm " + this.name + " of " + this.company);
    };
    
    var BillGates = new Person("Bill Gates");
    BillGates.SayHello();   //由于继承了原型的东西,规规矩矩输出:Hello, I'm Bill Gates
    
    var SteveJobs = new Person("Steve Jobs");
    SteveJobs.company = "Apple";    //设置自己的company属性,掩盖了原型的company属性
    SteveJobs.SayHello = function() //实现了自己的SayHello方法,掩盖了原型的SayHello方法
    {
        alert("Hi, " + this.name + " like " + this.company + ", ha ha ha ");
    };

    SteveJobs.SayHello();   //都是自己覆盖的属性和方法,输出:Hi, Steve Jobs like Apple, ha ha ha 
    
    BillGates.SayHello();   //SteveJobs的覆盖没有影响原型对象,BillGates还是按老样子输出

Object prototype object can be hidden to those properties and methods, a constructor prototype can also cover up the upper object constructor prototype objects and methods of the existing property. Just cover up the fact that objects at them to create a new property and method, but these attributes and methods of those objects with the prototype of the same name only. JavaScript is used to cover up this simple mechanism to achieve the object of "multi-state" nature of the target language with a static virtual function and overloading (override) happens to coincide with the concept.

However, more than the static object language are magic, we can always give the prototype to add a new dynamic object properties and methods, which dynamically extend the base class of functional properties. This static object language is very difficult to imagine. We look at the following code:

Js code

  1. function Person (name)
  2. (
  3. this. name = name;
  4. );
  5. Person.prototype.SayHello = function () / / set up the definition of the object before the Ways
  6. (
  7. alert ( "Hello, I'm" + this. name);
  8. );
  9. var BillGates = new Person ( "Bill Gates"); / / set up object
  10. BillGates.SayHello ();
  11. Person.prototype.Retire = function () / / set up the object after the dynamic expansion of the prototype approach
  12. (
  13. alert ( "Poor" + this. name + ", bye bye!");
  14. );
  15. BillGates.Retire (); / / dynamic expansion method may be previously set up the object of an immediate call

 function Person(name)
    {
        this.name = name;
    };
    
    Person.prototype.SayHello = function()  //建立对象前定义的方法
    {
        alert("Hello, I'm " + this.name);
    };
    
    var BillGates = new Person("Bill Gates");   //建立对象
    
    BillGates.SayHello();
    
    Person.prototype.Retire = function()    //建立对象后再动态扩展原型的方法
    {
        alert("Poor " + this.name + ", bye bye!");
    };
    
    BillGates.Retire(); //动态扩展的方法即可被先前建立的对象立即调用

Thor Kanami Buddha, the prototype could be playing a succession of such magic!

Prototype expansion

Presumably high-jun's savvy, perhaps you may want to do: If the built-in JavaScript such as those, such as Object and Function of the prototype function to add some new methods and attributes, are not able to extend the JavaScript functions?

Well, Congratulations, you have been!

At the rapid development of AJAX technology today, many successful AJAX runtime JavaScript projects are large-scale expansion of the built-in functions of the prototype function. Such as Microsoft's ASP.NET AJAX, given these built-in functions and prototype added many new features, thus increasing the JavaScript function.

We look at a section of code from MicrosoftAjax.debug.js:

Js code

  1. String.prototype.trim = function String $ trim () (
  2. if (arguments.length! == 0) throw Error.parameterCount ();
  3. return this. replace (/ ^ \ s + | \ s + $ / g,'');
  4. )

String.prototype.trim = function String$trim() {
    if (arguments.length !== 0) throw Error.parameterCount();
    return this.replace(/^\s+|\s+$/g, '');
}






  1. / / Define constructor
  2. function Person (name)
  3. (
  4. this. name = name; / / in the constructor in the definition of a member of
  5. );
  6. / / Method definition to the constructor of the prototype on
  7. Person.prototype.SayHello = function ()
  8. (
  9. alert ( "Hello, I'm" + this. name);
  10. );
  11. / / Subclass constructor
  12. function Employee (name, salary)
  13. (
  14. Person.call (this, name); / / call constructor upper
  15. this. salary = salary; / / expand the membership
  16. );
  17. / / Subclass constructor required by the upper first constructor to set up prototype object, the concept of implementation inheritance
  18. Employee.prototype = new Person () / / only required method of its prototype, a member of this object does not have any meaning!
  19. / / Subclass method definition to the constructor above
  20. Employee.prototype.ShowMeTheMoney = function ()
  21. (
  22. alert (this. name + "$" + this. salary);
  23. );
  24. var BillGates = new Person ( "Bill Gates");
  25. BillGates.SayHello ();
  26. var SteveJobs = new Employee ( "Steve Jobs", 1234);
  27. SteveJobs.SayHello ();
  28. SteveJobs.ShowMeTheMoney ();

    //定义构造函数
    function Person(name)
    {
        this.name = name;   //在构造函数中定义成员
    };
    
    //方法定义到构造函数的prototype上
    Person.prototype.SayHello = function()
    {
        alert("Hello, I'm " + this.name);
    };    
    
    //子类构造函数
    function Employee(name, salary)
    {
        Person.call(this, name);    //调用上层构造函数
        this.salary = salary;       //扩展的成员
    };
    
    //子类构造函数首先需要用上层构造函数来建立prototype对象,实现继承的概念
    Employee.prototype = new Person()   //只需要其prototype的方法,此对象的成员没有任何意义!
    
    //子类方法也定义到构造函数之上
    Employee.prototype.ShowMeTheMoney = function()
    {
        alert(this.name + " $" + this.salary);
    };
    
    var BillGates = new Person("Bill Gates");
    BillGates.SayHello();    
    
    var SteveJobs = new Employee("Steve Jobs", 1234);
    SteveJobs.SayHello();
    SteveJobs.ShowMeTheMoney();

Prototype class model can not simulate real private variables, but also in two parts to define the categories, seems not very "elegant." However, object methods are shared, will not encounter the issue of garbage collection, and the performance is superior to "closure" model. Is the so-called "being there" with them.

In the prototype model, in order to achieve types of inheritance, you must first sub-class constructor's prototype is set to a parent class object instance. Create the parent object instance constituted for the purpose of the prototype chain to play a role in sharing the top prototype method. However, examples of the creation of this object, the upper constructor will set the object to its members, members of the succession of these objects is meaningless. Although we do not pass parameters to the constructor, but it does create a number of members of no use, although its value is undefined, this is a waste ah.

Alas! The world nothing is perfect ah!