js--really understand object-oriented __js

Source: Internet
Author: User
Tags closure prototype definition

Several data types of JS: Number, String, Boolean, object, undefined five types of data

Common built-in object classes for JS: Date, Array, Math,number,boolean, String, RegExp, Function,object.

Two types of JS methods to judge: typeof, Instanceof

typeof: Unary operator, eg:typeof (1) returns number. It returns several top-level data types

Instanceof: The two-dollar operator eg:myobj instanceof MyObj returns a Boolean value. Applying a data type includes a class that you define. To determine whether a variable is an instance of this class, it and typeof can only be applied to JS built-in and custom data types, excluding DOM pairs such as window,document.

The data type that our platform declares is the subtype of number,string,boolean,object undefined and its object. The type of declaration also has a natural approach to the type of the owning, and is commonly used with a string-type Substring,indexof,length method. The main is to master the type defined by the function.

We can use function to declare a function, or to create a keyword for a class. When used as a function keyword, there is nothing to say. But as a keyword to create a class, we need to know some of the characteristics of JS. (use function as a keyword or class keyword, depending on your purpose). When we use the Function keyword, JS object-oriented features are basically not used, so it is not much to say. Now let's talk about function as a class of keywords, we need some common JS features to suit our three main characteristics of object-oriented: encapsulation, inheritance, polymorphism.

1, the package of:

Type in other object-oriented languages, using curly braces to qualify the scope of the variable. So there's the local variable. If the declaration is on the outermost side, it is a global variable. So what's missing now. is the member variable. Fortunately, JS supports closure features such as:

   function person () {
            var name= "John";
            var sex = "male";
            return {
                   ' getName ': function () {return
                            name;
                   },
                   ' Getsex ': function () {return
                            sex;
                   },
                   ' SetName ": function (_name) {
                            name=_name;
                   },
                   " Setsex ": function (_sex) {
                            sex = _sex;
                   },
                   " AliasName ": name;}
            ;        
         }
                   var person = new person ();
                   alert (person.name);//undefined
                   alert (Person.getname ());//John
                   Person.setname ("Li Guo")
                   ; Alert (Person.getname ());//Li Guo

This allows you to have a private member variable. Public member variables, which can be accessed directly, like the AliasName attribute. This is very basic. As we all know, in the Java language, there is this keyword

To represent the right image itself. And just JS also has this. But this and the other oriented to the language of this is a difference, where the difference is not to say.

We first use this to implement the class:

     function person () {
                   var name= "Harry";
                   var sex = "male";
                   This.aliasname= "123";
                   This.setname=function (_name) {
                            name=_name;
                   };
                   This.getname=function () {return
                            name;
                   };
                   This.setsex=function (_sex) {
                            sex=_sex;
                   };
                   This.getsex=function () {return
                            sex;
                   }
         }
         Test
         var person = new person ();
         alert (person.name);//undefined
         alert (Person.getname ());//John
         Person.setname ("Li Guo")
         ; Alert (Person.getname ());//Li Guo
         person.aliasname= "nnd";
         alert (person.aliasname);

Let's take a look at the person = The new person () execution: Person=new Object ()--> bind the this to the person type to This-->person.

Let's think about it, this is also the closure feature used. Because of the method of person, the external variable is referenced, and when the person is not reclaimed, the external variable is not reclaimed, but can only be accessed through the method of person. be wrapped up. However, this approach is much more flexible than the first one to achieve. Here is to say, this is different from the other language of this, think about it, JS functions can be used as a function can also do class, when a function contains this, but was directly called, like person (). Then JS will be related to the method attribute to window (this is not pointed to an object, will default to window), the execution process: This-->window. In this case, there is a certain degree of danger, because all the things in this class are global. Like what:

       Person ();
       Alert (Window.getname ());

So far, the creation of closed objects is said to be finished. At the moment we look at it like a class, but there is also a bit of each new person (), not only the attribute produces a copy, the method also produces a copy.

attribute produces a copy, this should be, but the method produces a copy is not necessary. JS function type data (remember), it provides prototype this property, that is, the prototype.

So write person:

<span style= "White-space:pre" >	</span>function person () {
                   var name= "Harry";
                   var sex = "male";
                   This.aliasname= "123";
                   This.self = person;
                   This.self.prototype.setname=function (_name) {
                            name=_name;
                   };
                   This.self.prototype.getname=function () {return
                            name;
                   };
                   This.self.prototype.setsex=function (_sex) {
                            sex=_sex;
                   };
                   This.self.prototype.getsex=function () {return
                            sex;
                   }
         }

All the person created will have a copy of the method. In order to prove correctness, you can respectively:

<span style= "White-space:pre" >	</span><span style= "White-space:pre" >	</span>var person = new Person ();
        var person1 = new Person ();
        alert (person.getname===person1.getname);

Take a look at the effect on it. Why the prototype can provide this effect.

Here, let's talk about prototype prototype and its related applications.

The prototype is a very important concept in JS, each function (the function in JS is also an object) has a property called prototype, but in general its value is NULL, but it has a very important function that the instance will share its properties and methods ( This is the basis of the implementation of JS. As an example:

<span style= "White-space:pre" >	</span>function auth () {
        <span style= "White-space:pre" >	</span>alert (this.name);
        <span style= "White-space:pre" >	</span>//Here you must add this keyword
<span style= "White-space:pre" >	</span>}
<span style= "White-space:pre" >	</span>auth.prototype.name= ' Shiran ';/This sentence can be placed after the object definition, but must be preceded by a call to
<span style= "White-space:pre" >	</span>new auth ();//This must be new.

Here are three points to note:

First, the name must be preceded by the keyword this, otherwise you will not get any, because if you do not add this, he will not be found in the prototype (plus this is a property it will be found in the context).

Second, if an instance object cannot find a property or method in the object to find it in the object's prototype, if you want to call the object's properties or methods when the function is invoked, you must place the calling statement after the prototype definition (here, the new Auth must come after auth.prototype.name).

Third, only instance objects are found in the prototype, because for the original object prototype is his property must be prototype to access (here, to use the new Auth () to generate an instance, not auth).

A prototype is shared with an instance of an object, which is both convenient to the program and confusing to people, with many unexpected results.

<span style= "White-space:pre" > </span>auth=function () {}; <span style= "White-space:pre" > </span>auth.prototype={<span style= "White-space:pre" > </span >name:[], <span style= "White-space:pre" > </span>getnamelen:function () {<span style= "White-space:
Pre "> </span>alert (this.name.length); <span style= "White-space:pre" > </span>, <span style= "White-space:pre" > </span>setname: function (n) {<span style= "White-space:pre" > </span>this.name.push (n); <span style= "White-space:pre" > </span&gt} <span style= "White-space:pre" > </span>} <span style= "White-space:pre" > </
Span>var lwx=new auth ();
<span style= "White-space:pre" > </span>lwx.setname (' lwx ');
<span style= "White-space:pre" > </span>lwx.getnamelen ();
<span style= "White-space:pre" > </span>var shiran=new auth (); <span style= "White-space:pre" > </span>shiran.setName (' Shiran '); <span style= "White-space:pre" > </span>shiran.getnamelen ();

The Second pop-up dialog box shows that the length of name is already 2. This is caused by the sharing of the prototype, because both the variable lwx and Shiran are auth objects, and the Name property is defined in the prototype of the Auth object, so the Name property is shared between Lwx and Shiran instances. But that's not the result we want to see, because we want each instance to be isolated from each other.

Here we can remove the name attribute from the prototype and place it in the definition of the Auth object:

<span style= "White-space:pre" >	</span>auth=function () {
<span style= "White-space:pre" >		</span>this.name=[];//Remember, be sure to precede this with this keyword
<span style= "White-space:pre" >	</span>} ;

As a result, each Auth instance will have its own name attribute. So we recommend that you define objects in the future by putting them in the definition and putting the methods of the objects into the prototype.

With the prototype, there is actually a class method and class attributes, the complete class has, the package member also has.

2, Inheritance:

Inheritance, we need to familiarize ourselves with the function in JS two functions, they are call and apply below, we first introduce them, know them, inheritance is almost.

There's a call and apply method in JavaScript that's basically the same, but there's a slight difference. First look at the JS manual in the explanation of call:

Call method

Invokes one of the object's methods to replace the current object with another object.

Call ([thisobj[,arg1[, arg2[, [,. argn]]]]

Parameters

Thisobj

Options available. The object that will be used as the current object.

Arg1, Arg2, argn.

Options available. A sequence of method parameters is passed.

Description

The call method can be used to invoke a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by Thisobj. If the thisobj parameter is not supplied, the global object is used as a thisobj. To be clear is to change the inner pointer of an object, that is, to change the content that this object is pointing to. This is sometimes useful in the object-oriented JS programming process.

Quote a piece of code on the Web, after running naturally understand its rationale.

JS Code:

<input type= "text" id= "MyText"   value= "input text" >  
<script>  
   function Obj () {this.value= "object. ";}   
   var value= "global variable";  
   function Fun1 () {alert (this.value);}  
 
   Window. Fun1 ();   Global variable  
   fun1.call (window);  Global variable  
   fun1.call (document.getElementById (' MyText '));  Input text  
   fun1.call (new OBJ ());   Object.  </script> 
<input type= "text" id= "MyText"   value= "input text" >
<script>
    function Obj () {this.value= object. ";}
    var value= "global variable";
    function Fun1 () {alert (this.value);}
 
    Window. Fun1 ();   Global variable
    fun1.call (window);  Global variable
    fun1.call (document.getElementById (' MyText '));  Input text
    fun1.call (new OBJ ());   Object.
</script>

The first parameter of the call function and the Apply method is the object to pass to the current object, and this within the function. Subsequent arguments are parameters that are passed to the current object.

JS Code:

<script>  
   var func=new function () {this.a= "func"}  
    var myfunc=function (x) {  
        var a= "MyFunc";  
       alert (THIS.A);  
       alert (x);  
   }  
   Myfunc.call (func, "Var");  
</script> 
<script>
   var func=new function () {this.a= "func"}
    var myfunc=function (x) {
        var a= "MyFunc";
        alert (THIS.A);
        alert (x);
    }
    Myfunc.call (func, "Var");
Visible Func and Var are ejected separately. Here we have an idea of the meaning of every parameter of call.

Both apply and call are the same in effect, but they differ in their parameters. The same is true for the first parameter, but for the second argument: Apply is passed an array of arguments, that is, multiple arguments are grouped into an array, and call is passed as a call parameter (starting with the second argument). such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding apply is written as: Func.apply (FUNC1,[VAR1,VAR2,VAR3))

The advantage of using apply at the same time is that the arguments object of the current function can be passed in directly as the second argument to apply. We use call to write an example of inheritance, like:

  function Animal () {
         this.name= "GG";
         This.getname=function () {alert (this.name)};
    function person () {
         animal.call (this);//construct parent class
         this.aliasname= "";
    }

   function init () {
         var p = new person ();
         P.getname ();
   }
   Write another apply function: function
    Animal (name,sex) {
                   this.name= "GG";
                   This.getname=function () {alert (this.name+name+sex)};
    function Person (name,sex) {
                   animal.apply (this,[name,sex]);//construct parent class, parameter is array
                   this.aliasname= "";
    }
 
   function init () {
                   var p = new Person ("WSK", ' Mans ');
                   P.getname ();
   }

3, polymorphism:

Polymorphism is simpler for JS, because it is a weakly typed language and can pay any type of variable for a variable. It doesn't exactly fit, but it can be used.

JS object-oriented programming, there are quite a long test, I hope to give a friend just started to provide a help.

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.