Several ways to define classes and objects (1/4)

Source: Internet
Author: User

means that you do not need to check the object type before the program runs, as long as you check that the object supports attributes and methods. You can perform a large number of operations on an object without any penalty before binding.
The above code appears in the "pre-declaration" phenomenon, we can greatly use the "late binding" mechanism to explain. In the scope of a function, all variables are "late bound". That is, the declaration is top-level. So the code above is consistent with the following:
Copy code code as follows:

var a = ' global ';
(function () {
var A;
alert (a);
A = ' local ';
})();

Only a declaration was made to a before alert (a) and no value was assigned. So the results are predictable.

<!--digression to this end-->
RT: What this article is saying is that in the web effects, I know several ways to define classes and objects: <! --statement: Most of the following comes from "JavaScript advanced Programming", but the individual narrative way is different-->
"Direct Volume Method"
Using direct volume to build objects is the most basic way, but there are many drawbacks.
Copy code code as follows:

var obj = new Object;
Obj.name = ' sun ';
Obj.showname = function () {
Alert (' THIS.name ');
}

We built an object obj, which has a property name, a method showname. But what if we're going to build a similar object? Do you want to repeat it again?
No! , we can implement it with a factory function that returns a particular type of object. Like a factory, the output of an assembly line is the specific type of result we want.
"Factory mode"
Copy code code as follows:

function Createobj (name) {
var tempobj = new Object;
Tempobj.name = name;
Tempobj.showname = function () {
alert (this.name);
};
return tempobj;
}
var obj1 = createobj (' Obj_one ');
var obj2 = createobj (' Obj_two ');

Home 1 2 3 4 last page

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.