Basic Review of Javascript (3) Javascript object-oriented, javascriptjs

Source: Internet
Author: User

Basic Review of Javascript (3) Javascript object-oriented, javascriptjs

This is the last article in the expression series from simple to deep, but recently the team has been busy and never been busy! However, if you like expressions, please rest assured that some basic principles of Javascript are common in your work, so I decided to spend some time organizing the basic knowledge and sharing it with you. A training PPT will be attached later. I was planning to write an article at the beginning, but later I wrote it and found more and more articles. So I decided to write a series. All content in this series involves Javascript basics, and there are no trendy things, but I believe these basic things will help you understand those interesting things.

  • Basic Review of Javascript (1) Type
  • Basic Review of Javascript (ii) Scope
  • Basic Review of Javascript (3) Object-oriented

This article is the third part of the Javascript series that you must know. We will mainly look at how Javascript is object-oriented programming. It mainly involves the following:

  • Objects in Javascript
    • What is an object?
    • Traverse attributes
  • Create object
    • Factory Model
    • Constructor Mode
  • Details about this
    • In the function
    • In the object Method
    • In the constructor
    • In call and apply
    • In bind
    • In the dom element event processing function
  • Prototype
    • What is prototype?
    • What is prototype chain?
    • Use prototype chain to implement inheritance
    • Problems in prototype chain

Objects in Javascript

What is an object?

We can understand objects in Javascript as a group of unordered key-value pairs, just like Dictionary <string, Object> in C. Key is the attribute name, and value can be of the following three types:

  1. Basic Value (string, number, boolean, null, undefined)
  2. Object
  3. Function
Var o = new Object (); o ["name"] = "jesse "; // The basic value is used as the object property o ["location"] = {// The object is used as the object property "city": "Shanghai", "district": "minhang "}; // function as the object property o ["sayHello"] = function () {alert ("Hello, I am" + this. name + "from" + this. location. city);} o. sayHello ();

Traverse attributes

In C #, we can use foreach to traverse the Dictionary <string, Object>. If an Object is a set of key-value pairs in Javascript, how can we traverse it?

for (var p in o) {  alert('name:'+ p +      ' type:' + typeof o[p]    );}// name:name type:string// name:location type:object// name:sayHello type:function

The Traversal method above includes attributes in the prototype. We will discuss what prototype is and how to differentiate attributes in the prototype and instance.

Create object
In fact, we have created an object and used the following two methods to create an object.

  1. Use new to create an Object instance.
  2. Literal

The above o is created in the first way, while the location attribute in o is created in the literal way. The first method is called the constructor mode, because the Object is actually a constructor and generates an Object instance for us. If you still have any questions about the constructor, check out my first basic Object and object type.

In addition to the above two methods, let's take a look at some ways to create objects:

Factory Model

function createPerson(name, age, job){  var o = new Object();  o.name = name;  o.age = age;  o.job = job;  o.sayName = function(){    alert(this.name);  };  return o;}var person1 = createPerson('Jesse', 29, 'Software Engineer');var person2 = createPerson('Carol', 27, 'Designer');

There is a problem with the Object created in this mode, that is, it creates an Object instance for me within the function. This instance has nothing to do with our constructor createPerson.

Because I used new Object () internally to create this Object, it is an Object instance. So if we want to know which function is an instance, it is impossible.

Constructor Mode

The factory mode does not solve the problem of Object recognition, but we can think that Object () is actually a function, but when I add a new one before it, it becomes an instance where the constructor generates an Object for us. Then I can add new in front of other functions to generate the function instance. This is the so-called constructor mode.

function Person(name, age, job){  this.name = name;  this.age = age;  this.job = job;  this.sayName = function(){    alert(this.name);  };}var p1 = new Person('Jesse', 18, 'coder');alert(p1 instanceof Person); // true

Details about this
This can also be regarded as a magical object in Javascript. It is true that this is an object. In the previous article, we talked about the variable object in the scope and scope chain. The variable object determines which attributes and functions can be accessed in the current execution environment, to some extent, we can regard this as the variable object. We mentioned earlier that the largest execution environment is the global execution environment, and the window is the variable object in the global execution environment. In the global environment, this = window will return true.

In addition to the global execution environment, we also mentioned another execution environment, that is, the function. Each function has a this object, but sometimes the values they represent are different, mainly determined by the caller of this function. Let's take a look at the following scenarios:

Function

function f1(){ return this;}f1() === window; // global object

Because the current function runs in the global function, the this object in the function points to the global variable object, that is, window. In this mode, undefined is returned in strict mode.

Object Method

var o = { prop: 37, f: function() {  return this.prop; }};console.log(o.f()); // logs 37

In the object method, this object points to the current instance object. Note: No matter where or how the function is defined, as long as it is a method of an object instance, its "this" points to this object instance.

var o = { prop: 37 };var prop = 15;function independent() {  return this.prop;}o.f = independent;console.log(independent()); // logs 15console.log(o.f()); // logs 37

Difference: if the above function is directly executed by independent, this is to point to the global execution environment, then this. prop is to point to our global variable prop. However, if you set independent as an attribute of object o, this in independent points to this instance. Similarly, this. prop becomes the prop attribute of object o.

Constructor

We mentioned above that using constructors to create objects actually utilizes this feature. In constructor, this object points to the object instantiated by this constructor.

function Person(name, age, job) {  this.name = name;  this.age = age;  this.job = job;  this.sayName = function () {    alert(this.name);  };}var p1 = new Person('Jesse', 18, 'coder');var p2 = new Person('Carol',16,'designer');

When we instantiate Person to get p1, this points to p1. When we instantiate Person to get p2, this points to p2.

Use call and apply

When we use call and apply to call a function, the this object in this function will be bound to the object we specified. The main difference between call and apply is that apply requires an array to be input as the parameter list.

Function add (c, d) {return this. a + this. B + c + d;} var o = {a: 1, B: 3}; // The first parameter is bound to the this object add of function add. call (o, 5, 7); // 1 + 3 + 5 + 7 = 16 // The second parameter is the array as the arguments Input Method addadd. apply (o, [10, 20]); // 1 + 3 + 10 + 20 = 34

In the bind method

The bind method is the function. prototype. bind in the Function prototype. That is to say, all functions have this method. But when we call the bind of a method, we will generate a new method that is the same as the original method, but this is the first parameter that points to the bind we passed.

function f() {  return this.a;}var g = f.bind({ a: "azerty" });console.log(g()); // azertyvar o = { a: 37, f: f, g: g };console.log(o.f(), o.g()); // 37, azerty

In the dom element event Processor

In the event processing function, this points to the dom element that triggers the event.

HTML code

JavaScript code

function click(e) {  alert(this.nodeName);}var myDiv = document.getElementById("mydiv");myDiv.addEventListener('click', click, false);

When we click the div on the page, there is no doubt that it will display the DIV.

Prototype
Prototype is a prototype, which is also an important concept in Javascrip. Before talking about the prototype, we need to review the previous constructor pattern. This feature is mainly used when we use constructors to create objects.

function Person(name, age, job) {  this.name = name;  this.age = age;  this.job = job;  this.sayName = function () {    alert(this.name);  };}var p1 = new Person('Jesse', 18, 'coder');var p2 = new Person('Carol', 17, 'designer');

We also mentioned above that when the Person instantiates p1, this in Person points to p1. When the Person instantiates p2, this points to p2. That is to say, although sayName in p1 and p2 plays the same role, they are not actually a function.

That is to say, there are multiple copies in their memory heap, instead of referencing address copies in the stack. Not to mention that this character does not conform to the object-oriented idea, at least this is a waste of memory. The solution is the prototype we will discuss.

What is prototype?

Every function in Javascript has a prototype object, which is no different from common objects. However, by default, a constructor attribute points to this function. At the same time, all instances of this function will have a reference pointing to this prototype object. If you are not sure, take a look at the figure below:

The above is the constructor, the constructor prototype, and the relationship between instances. Taking our Person constructor as an example, all Person instances (p1, p2) are comfortable with a prototype attribute pointing to the Person constructor prototype object. In this way, we can write the method on the prototype, so all our instances will access the same method.

function Person(name, age, job) {  this.name = name;  this.age = age;  this.job = job;  Person.prototype.sayName = function () {    alert(this.name);  }}var p1 = new Person('Jesse', 18, 'coder');var p2 = new Person('Carol', 17, 'designer');alert(p1.sayName == p2.sayName); // true

What is prototype chain?

Do you still remember the scope chain? If you do not remember, Please consciously go to the second article to review (scope and scope chain ). To put it simply, when we access a variable in an execution environment, if this variable does not exist in the current execution environment, the variable will be found in the stage of the execution environment, that is, its outer layer. If the outer layer cannot be found, the other layer will be located until the global execution environment is found, this is the scope chain. The prototype chain is a bit of type, but the scenario is changed to our object instance. If I find an attribute in an instance, this instance does not, it will be found in its prototype. Remember, as we have mentioned above, prototype is also an object, and it also has its own prototype object, so it becomes a chain and cannot be found in the prototype of the Instance itself, find the prototype Object in the prototype Object and extend it to the prototype Object of the Object, by default, the prototype Object of the function we created points to the prototype Object of the Object, so that's why we can call the Object method (toString, valueOf) on the instance of our custom constructor ).

Use prototype to implement inheritance

In fact, we have already discussed the implementation of inheritance in Javascript, mainly relying on the prototype chain. All instances inherit from objects because by default, all prototype objects of the created Function Point to the object. Similarly, we can define our own inheritance relationships.

Function Person (name, age, job) {this. name = name; this. age = age;} Person. prototype. sayName = function () {alert (this. name);} function Coder (language) {this. language = language;} Coder. prototype = new Person (); // point the Coder prototype to a Person instance to implement the following steps. prototype. code = function () {alert ('I am a' + this. language + 'developer, Hello World! ');} Function Designer () {} Designer. prototype = new Person (); // point the design prototype to a Person instance to implement the following steps. prototype. design = function () {alert ('in fact, I am just a map worker .... ');} Var coder = new Coder ('C #'); coder. name = 'jesse '; coder. sayName (); // Jessecoder. code (); // I am a C # developer, Hello World! Var designer = new Designer (); designer. name = 'carol '; designer. sayName (); // Caroldesigner. design (); // In fact, I am just a painter ....

Problems in prototype chain

Because the prototype object is saved as a reference, we should pay special attention when assigning values. Accidentally, the previously assigned value may be assigned. For example, in the above Code, we first write the prototype method and then implement inheritance, then our prototype method will be gone.

Function Coder (language) {this. language = language;} Coder. prototype. code = function () {alert ('I am a' + this. language + 'developer, Hello World! ');} Coder. prototype = new Person (); // all the prototype attributes and methods above will be overwritten. var coder = new Coder ('C # '); coder. name = 'jesse '; coder. sayName (); coder. code (); // an error is reported. The code method cannot be found.

All three articles have been completed.

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.