Class and closure _ js object-oriented in Javascript

Source: Internet
Author: User
First of all, we need to declare that at least no class exists in Javascript so far. The so-called "class" is actually not a real class, it is just like a class in other object-oriented languages. Its essence is Function + prototype ). Some people say that javascript is also object-oriented, but it is prototype based. Of course, this is only a conceptual difference. I don't want to discuss whether javascript is object-oriented, the key is to explain that although javascript classes behave much like classes in other languages, the internal implementation mechanisms are indeed inconsistent. If we blindly compare the classes in javascript as classes in other languages, sometimes the brain gets confused.

Let's take a look at a simple piece of code. Generally, this is the case when we introduce how to create a class in the teaching material (of course there are more complicated methods, but they are essentially the same ):

The Code is as follows:


Function MyClass (x ){
This. x = x;
}
Var obj = new MyClass ('Hello class ');
Alert (obj. x );


Undoubtedly, obj has an x attribute. The current value is Hello class. But what is obj? MyClass is just a function, which is called a constructor. In other OO languages, constructor should be placed inside the class keyword, that is, a class should be declared first. In addition, what is this in the function body? In other OO languages, the concept of this is very clear, that is, the current object, because it has declared the class before the constructor is executed, and some internal fields of the class have been defined.

First, in javascript Functions, this keyword indicates the scope of the function to be called. The concept of scope is not very easy to understand. However, you can simply think of it as the object that calls the function. Let's look at the MyClass function. What is this inside it?

If we change the code:

The Code is as follows:


Var obj = MyClass ('Hello class ');


This is fully syntactic. If this code is run in a browser, You can debug it and find that this is a window object. There is no relationship with obj. obj is still undefined, and alert does not have any results. The reason why the original code can work is the credit of the new keyword. The new Keyword converts a common function into a constructor. That is to say, MyClass is still a common function. It is basically new because it can construct an obj. When a function has a new keyword, javascript creates an anonymous object and sets the current function scope to this anonymous object. Then, if this is referenced inside the function, it is the referenced anonymous object. Finally, even if this function does not return, it will return this anonymous object. Then obj naturally has the x attribute.

Now this MyClass is a bit like a class. However, this is not all about new jobs. Javascript can also easily implement inheritance-relying on prototype. prototype is also an object. After all, except for the original type, everything is an object, including a function. More importantly, javascript is prototype based, which means that there is no class concept in javascript, and the class does not exist. A function represents a class, prototype. prototype can have various attributes, including functions. In the process of constructing an object, the new mentioned in the previous section will copy the attributes of the prototype of the function to the object one by one before returning the anonymous object. Here, copying refers to a copy reference, instead of a new object. Copying the content is equivalent to retaining the prototype reference of a function that constructs it. Some textbooks vaguely say that all "all objects have a prototype attribute", which is inaccurate. Although it does have a prototype attribute, it is invisible to the outside world. Only function objects have the prototype attribute, and function objects have a constructor attribute by default.

See the following code:

The Code is as follows:


Function MyClass (x ){
This. x = x;
}
Var proObj = new MyClass ('x ');
InheritClass. prototype = proObj;
MyClass. prototype. protox = 'xxx ';
Function InheritClass (y ){
This. y = y;
}
Var obj = new InheritClass ('Hello class ');
MyClass. prototype. protox = 'changed ';
ProObj. x = 'changed too ';
Alert (obj. protox );
Alert (obj. x );


The output result is changed and Changed Too. This Code indicates that the object retains the prototype reference of the constructor. Note that proObj also retains the prototype reference of its constructor. If you change the code:

The Code is as follows:


Var obj = new InheritClass ('Hello class ');
ProObj. protox = 'I am winner ';
MyClass. prototype. protox = 'changed ';
ProObj. x = 'changed too ';
Alert (obj. protox );
Alert (obj. x );


The output is I am winner and Changed Too. In fact, these prototypes are referenced layer by layer, forming a prototype chain. When reading the attributes of an object, first look for its own defined attributes. If not, find the hidden prototype attribute layer by layer. However, when writing an attribute, it overwrites its reference and does not affect the prototype value.
Next, let's introduce the closure. First of all, the closure here is not a concept in the transfer closure of the relationship between the closure (closure) and discrete mathematics. I thought there was a correlation between them. Later I thought about it carefully, it seems that there is no association, just the same name. First look at the definition:
Closure
A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression ).
To fully understand the closure, you need to have a thorough understanding of the mechanism of Javascript functions. This mechanism is a bit complicated and not clear in a few words. If you are interested, you can refer to Javascript clousures here. even in this article, I just talked about the principle. The general idea is that all function calls are executed in a running Context. In this Context, there is a scope object, including the local variables and parameters of the function. In addition, if a function is an internal function, its scope contains the scope of its external function. When an internal function encounters a variable name, it starts from the internal scope and keeps searching for the outer scope. Therefore, if an internal function returns an external function as an object, the internal function will not be released even if the external function has been executed, because its internal function still references it, because internal functions have external function scopes, local variables of external functions are not released. This constitutes the closure.
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.