JS's this and object-oriented programming

Source: Internet
Author: User

It is strange that a lot of books or information have not been made clear about this matter.

The key is that there is not a holistic thinking technology model, the problem is isolated so it is not easy to understand.

Let's first look at this, which is the keyword of JS, which indicates the context object of the function.

Here's the problem, like:

?
1 2 3 4 5 6 7 8 9 10 11 var obj = {};   obj.name = ‘test‘;   obj.output = function () {       console.log(this.name); };obj.output();

This specifies the context object, which, of course, is assigned to a global variable if not specified, window, which is the source of the problem. So the best solution is to use the ' using strict ' strict mode, one error, the more easy to locate the problem.

In the case of strict mode, let's see where the problem occurs.

When renaming variables:

For example, above, Console.log (obj.name), without this, then in other code obj is defined by another variable, obviously error. But with this, the code environment becomes a problem.

For example, we re-construct this object into a constructor:

function OBJ (name) {

....

Use the This keyword.

But the constructor is also a function, and a little attention will be taken as a normal function call. Without new, it becomes like this.

OBJ (' Test ') ...

At this point the constructor is run in error, and it is not going to make a mistake. In the non-strict mode, this point of the constructor points to the global window, which is the biggest flaw of JS. Not only do not get the correct results, but also pollute the overall situation. In a large number of JS, the erroneous invocation of a constructor is a disastrous result.

Why object-oriented programs like C#,java don't have this problem? Because they use the Class keyword, class cannot be used in the definition phase (unless explicitly defined static properties and methods)

It can be seen that this serious this, JS, not only the problem of global variables, but also affect the entire constructor for the other side of the programming, so the safe way to write the constructor is necessary, is not new, but also to construct.

Of course ' use strict ' is just a symptom. The cure is for new and not new to have consistent results.

JS Constructor, if run directly, then the return result is the object, this definition of the object is discarded, very special point. So simply do not define this with new and use the returned object directly.

?
1 2 3 4 5 6 7 8 9 10 11 12 function pClass() {     this.Name = ‘test‘;     this.output = function () {         console.log(this.Name);     }     return new pClass(); }var p1 = pClass(); var p2 = new pClass(); p1.output(); p2.output();

Instead of new, the first problem is resolved, but if new becomes a nested call. Error. Obviously, the error is because this, so we are inside, directly define the object return, make the real "constructor"

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 function pClass() {    return {         Name: ‘test‘,         output: function () {             console.log(this.Name);         }     } }var p1 = pClass(); var p2 = new pClass(); p1.output(); p2.output();

Again, the direct return object avoids the problem of this, but it is not tolerated, for example, that P1,P2 uses two instances of the output method.

So this led to JS in the processing of object creation can not provide an effective mechanism, this and new do not match, the complete solution is ES6, introduce the class keyword, otherwise, no matter how to create a perfect solution, and the code verbose.

On the ES5, the second best solution is:

1. Introduce ' use strict ' to prevent erroneous constructors and this

2. The first letter of the construction function capital, the other all hump, by naming to distinguish

3. Create objects using new, and use the simple prototype mode

4. Use module mode as much as possible in non-new form

5. The most critical place, the JS object is not a good, object-oriented programming is not the best way, should give priority to the combination of patterns, the object and method body apart, which from the root of the solution JS object weaknesses.

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.