Classes and closures in Javascript _js object oriented

Source: Internet
Author: User
Tags anonymous closure constructor
Some people say that JavaScript is also object-oriented, but it is prototype based, of course, this is only the conceptual difference, I do not want to discuss JS is object-oriented, the key is to show that although JavaScript classes behave like other languages in the class, But the internal implementation mechanism is not very consistent, if you blindly in the JavaScript class analogy in other languages of the class, sometimes the brain will be confused.

Take a look at a simple piece of code that describes how to create a new class in a general textbook (and, of course, a more complex approach, but essentially the same):
Copy Code code as follows:

function MyClass (x) {
this.x = x;
}
var obj = new MyClass (' Hello class ');
alert (obj.x);

There is no doubt that obj has an X attribute at this time, and now the value is Hello class. But, what exactly is obj? MyClass is just a function, which we call a constructor. In other OO languages, constructors are placed inside the class keyword, which means declaring a class first. Also, what is this in the body of the function? In other OO languages, the concept of this is clear, the current object, because it declares the class before the constructor executes, and some of the fields inside the class are already defined.

To explain, in JavaScript functions, the This keyword represents the scope (scope) that invokes the function, and the concept of the scope is not too well understood, as explained below. But you can simply think of it as the object that calls the function. And look at the MyClass function, what's this inside?

If we change the code to:
Copy Code code as follows:

var obj = MyClass (' Hello class ');

This is perfectly grammatical. If this code is running in a browser, debug it and you can see that this is the Window object. and obj has no relationship, obj or Undefined,alert will not have results. The original code can work, is the new keyword credit. The New keyword turns an ordinary function into a constructor. In other words, MyClass is still an ordinary function, it can construct an obj, basically is the credit of new. When the function has a new keyword, JavaScript creates an anonymous object and sets the scope of the current function to this anonymous object. Then referencing this in that function is the anonymous object referenced, and finally, even if the function does not return, it returns the anonymous object. Then obj naturally has the X attribute.

Now this MyClass has been a bit like a class. However, this is not the whole of new work. JavaScript is also easy to implement inheritance-depending on the Prototype.prototype is also an object, after all except the original type, all things are objects, including functions. More importantly, the previous reference to JavaScript is prototype based, meaning that there is no class concept in JavaScript, class is nonexistent, a function, it behaves like a class, is relying on the prototype. Prototype can have a variety of properties, including functions. In the process of constructing an object, the previous paragraph says that the property one by one in the prototype of that function is copied to the object before it finally returns the anonymous object. The copy here is a copy of the reference, not a newly created object, that replicates the content, within it, the equivalent of preserving a prototype reference to the function that constructs it. Some textbooks vaguely say that all "all objects have a prototype attribute" is not accurate, although it does have a prototype attribute, but external is not visible. Only the function object has a prototype property, and the prototype of the function object has a constructor property by default.

Look at the following code:
Copy Code code 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 results are changed and changed Too. This code illustrates that the object retains the prototype reference of the constructor, and note that Proobj is also a reference to the prototype of its constructor that is retained. If you change the code to:
Copy Code code 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 prototype are referenced by layers, forming a prototype chain. When reading the attributes of an object, first look for the attribute defined by itself, and if not, look for the prototype attribute implicitly within the layer. But when you write a property, it overwrites its reference, and it does not affect the value of the prototype.
To introduce the closure, first of all, the closure of the closure and discrete mathematics in the transitive closure of the relationship is not a concept, I once thought that there is a connection between them, and then carefully think about it, there seems to be no correlation, just the same name. First look at the definition:
Closure
A "closure" is a expression (typically a function) which can have free variables together and an environment that binds T Hose variables (that "closes" expression).
To fully understand that closures require a more thorough understanding of the mechanism of JavaScript functions, the mechanism is somewhat complex, not words, and interested friends can look at JavaScript clousures. Even this article, it is only about the principle of the next. The general effect is that any function call is executed in a run-time context (Execution contexts), which has a scope object that includes local variables, parameters, and so on for this function. In addition, if a function is an intrinsic function, its scope contains the scope of its external function. When an internal function encounters a variable name, it is found from within the scope and continues to the outer scope. Therefore, if an intrinsic function returns an external function as an object, even if the external function has finished executing, the intrinsic function is not released because the intrinsic function has a reference to it, because the internal function has the scope of the external function, so the local variable of the external function is not released. This constitutes a 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.