Note the following before getting started with javascript: Object Section

Source: Internet
Author: User

After reading a post recently, the landlord complained that JavaScript is not a standard object-oriented language, and it is barely an object-oriented language at most. This statement is also very practical in the market, mainly because the class-based programming language is too influential, C ++, Java, C # which is not the name of the door, now we can say that object orientation requires class keywords.

Object-Oriented development and programming is just a programming idea and Guiding Opinions on programming (the design pattern is also an induction and name of experience, which is definitely not from the Bible ). The idea of object-oriented is mainly to suggest developers to pay attention to the following: Implement code reuse as much as possible (procedural functions are also used by code reuse ), design a unique data type for a specific individual as much as possible. This unique type contains all self-completed operations of this type, but only discloses the data and functions that require the caller to care about, all others are blocked.

There is no specific agreement on how a specific language implements object-oriented development principles. For historical reasons, most of our object-oriented programming adopts the C ++ style static class method, so many of us are used to class-based object-oriented programming. In addition, the class starts from C ++ to Java and then to C #, the compiler vendor has made great efforts to help developers better understand the syntactic sugar, and has introduced many new features for Describing object encapsulation and inheritance, the keyword of the multi-state application greatly improves the development efficiency. Naturally, we also like class programming and naturally recognize class as the standard or spokesperson for object-oriented development.

Since we started to understand object-oriented programming, there are not only class-based methods, but also other methods. For example, VB is implemented based on implements (It's Too Late To remember, and Javascript is implemented based on prototype.

The special feature of JavaScript is that it has no class, and everything is an instance (here I use an instance rather than an object, I am worried that the object is not rigorous ), javascript provides six basic data types that can be accessed: undefined, null, Boolean, String, number, and object, the following code is a bit confusing when it is null. Others are quite normal because null is defined as null in JavaScript.

alert(typeof undefined);alert(typeof null);alert(typeof 123);alert(typeof 123.45);alert(typeof true);alert(typeof false);alert(typeof "Hello");alert(typeof {});

When it comes to null, we know that there are also strings, date, number, Boolean, object, and function in Javascript. in Java or C #, we can determine that these should be objects, it is also an implicit injection of the basic data type, but in Javascript, it is completely different.

alert(typeof Number);alert(typeof String);alert(typeof Date);alert(typeof Boolean);alert(typeof Function);alert(typeof Object);

All the above results are functions. This tells us two basic facts: 1. In JavaScript, only objects are the object data type (this is the only one); 2. Objects and functions are directly related to each other.

If the new operator is used for the above functions, the result is:

alert(typeof new Number());alert(typeof new String());alert(typeof new Date());alert(typeof new Boolean());alert(typeof new Function());alert(typeof new Object());

All objects except functions are returned. Now we start to enter the topic.

The simplest object definition in Javascript is to define the object using the literal.

var obj = {};var Poker = {    Title: "K",    Style: "spade",    Value: 13};

In the above code, we can get two objects. Remember that in Javascript, no class is used to abstract objects, and all values are instances. We can get an object without any class. Using {} is to declare an object instance. The values defined in such a direct object are public by default. It is not allowed to declare a private property in a literal object using VAR. It should be noted that the JavaScript Object is a set of key-value, and the attribute we are talking about is actually a key, correctly, three convenient keys: title, style, and value are defined in the poker. It is easy for programmers who use C # and Java to understand the attribute. Javascript encapsulates object orientation differently from class. It does not provide access modifiers such as public and private. If we use modern browsers such as ie9 and chrome that support ecmascript5, we can define keys that cannot be traversed and set and get for keys, in addition, you can specify a read-only key, which seems to be close to the habit of class. The following is a demo.

VaR OBJ = {}; var poker = {Title: "K", style: "Spade", value: 13, state: 1}; object. defineproperties (poker, {"backgroundimg": {value: "Images \ common \ hide.png", enumerable: false, // It is not allowed to traverse writable: false // read-only }, "forgroundimg": {value: "Images \ spade \ k.png", enumerable: false, // it cannot be used to traverse writable: false // read-only}, IMG: {get: function () {return this. state = 0? This. backgroundimg: This. forgroundimg;}, enumerable: true}); alert (poker. IMG); // images \ spade \ k.png for (var key in poker) {alert (key); // backgroundimg and forgroundimg cannot be traversed to} alert (poker. backgroundimg); // you can still access poker. backgroundimg = "XXX"; alert (poker. backgroundimg); // still images \ common \ hide.png

However, there are at least two troubles when defining objects using words. One is the difficulty of reusing objects, and the other is the encapsulation of private variables. Although the objects created literally can also be inherited, for example

VaR poker = {state: 1}; var pokera = {Title: "A", style: "Spade", value: 14, _ PROTO __: poker }; vaR poker10 = {Title: "10", style: "club", value: 10, _ PROTO __: poker}; alert (pokera. title); // aalert (pokera. state); // 1 alert (poker10.title); // 10 alert (poker10.state); // 1 // access alert (pokera. _ PROTO __. state); alert (poker10. _ PROTO __. state );

Because the literal objects in JavaScript are all instances, we don't care whether such inheritance is ugly or not, but at least we can realize that poker objects (instances always exist ), each successor needs a poker instance space.

Poker.State = 3;PokerA.State = 0;alert(PokerA.State); //0alert(Poker10.State); //3alert(Poker.State); //3

The following code clearly tells us that this points to a subclass in a poker instance (if you admit that this is a subclass)

var Poker = {    State: 1,    toString: function() {        alert(this.Style + this.Title + ":" + this.Value);    }};var PokerA = {    Title: "A",    Style: "spade",    Value: 14,    __proto__: Poker};var Poker10 = {    Title: "10",    Style: "club",    Value: 10,    __proto__: Poker};PokerA.toString(); // spadeA: 14Poker10.toString(); //club10:10

At the same time, we can understand that when a called key is not defined in the current object, it will be searched up along the inheritance chain, until the first key is found (the object's own tostring is ignored in this demo). If none of them exist, it is undefined. You can think of it as rewriting in class to realize polymorphism. I can say so.

Generally, I do not recommend that you use the literal (I am very uncomfortable using this word, and I like to call it a direct object) for inheritance. The most valuable usage of a direct object is to use it as a parameter or something, simple and efficient. If you want to use the memory reasonably and create objects flexibly, you must use the function to make it easier.

var Poker = function(style, title, value, state) {    this.Title = title;    this.Style = style;    this.Value = value;    this.State = arguments[3] === undefined ? 0 : state;    var backgroundImg = "images\\common\\hide.png";    var forgroundImg = "images\\spade\\" + title + ".png";    this.Img = (function(x) {        return x == 0 ? backgroundImg : forgroundImg;    } (this.State));    this.toString = function() {        return this.Style + this.Title + ":" + this.Value    }}var Poker10 = new Poker("spade", "10", "10");var PokerA = new Poker("spade", "A", "14", 1);alert(PokerA.toString()); // spadeA: 14alert(Poker10.toString()); //club10:10alert(PokerA.Title); //Aalert(PokerA.State); //1alert(Poker10.Title); //10alert(Poker10.State); //0alert(PokerA.Img); //images\spade\A.pngalert(Poker10.Img); //images\common\hide.png

The above code is obviously much more comfortable and easy to understand. I have no objection. The poker function is called a constructor. In fact, it does help us construct a poker object. However, JavaScript does not have the class concept, so I prefer to say: the poker function helps us construct a poker-based object. It can be called as a constructor.

Whether it is a direct object or an object constructed by a function, it is dynamic for Javascript. This instance can dynamically add keys.

Take a look at the following code. After constructing pkoner10 and pokera, we create a new createdom function on the poker prototype. This function is still effective for pkoner10 and pokera.

var Poker10 = new Poker("spade", "10", "10");var PokerA = new Poker("spade", "A", "14", 1);Poker.prototype.createDom = function() {    return $("

However, remember that the new function key must be added to prototype. The following code is incorrect.

Poker. Insert = function (box, poker) {poker. appentto (box);} pokera. insert ("body", pokera. createdom (); // Error

I guess this is the reason. A function is a function when it is used. When it is constructed using new, the compiler will point this to the key to prevent function prototype (prototype, here is a proof.

alert(Poker.prototype.constructor === Poker); //truealert(PokerA.constructor === Poker); //truealert(PokerA.createDom === PokerA.__proto__.createDom); //truealert(PokerA.__proto__.constructor === Poker.prototype.constructor); //true

When it comes to keys, let's just talk about the array in Javascript. The array is generally in the concept of static language, and the memory size is fixed in Chinese. However, arrays in JavaScript are actually object deformation.

var arr = [];for (var i = 0; i < 5; i++) {    arr[i] = i;}arr.push(99);for (var index in arr) {    alert(index); // 0 1 2 3 4 5}

The final for is not the value of the array, but the index of the array, so we can evaluate the value in this way.

var arr = [];for (var i = 0; i < 5; i++) {    arr[i] = i;}arr.push(99);for (var index in arr) {    alert(arr[index]);}

Therefore, it is estimated that arr [I] = I dynamically adds an attribute and assigns a value.

Back to the constructor, it generally seems that in order to meet the object-oriented programming meaning: an object is a set of its own data, therefore, we generally define the object attributes (that is, data) in the constructor. The data is provided by the constructor parameters, and the object methods are compiled externally by functions, and point to the prototype of the constructor. The reason is that the literal objects in Javascript do not have the property ......

This property is the instance constructed by the function. If you write the method directly on the function, it is the static member of the function. It is estimated that this is a demo.

function Poker(style, title, value) {    this.Style = style;    this.Title = title;    this.Value = value;}Poker.max = function(Poker1, Poker2) {    var p;    for (var i = 0; i < arguments.length; i++) {        if (arguments[i] instanceof Poker) {            if (typeof p == "undefined") {                p = arguments[i];            }            else {                p = p.Value > arguments[i].Value ? p : arguments[i];            }        }    }    return p;}var p = Poker.max(new Poker("club", "K", 13),            new Poker("diamond", "A", 14),            "",            new Poker("diamond", "10", 10));alert(p.Style + p.Title + "[" + p.Value + "]"); // diamondA[14]

What is the prototype relationship between functions, constructors, and objects? The following code describes these relationships.

alert(Poker.constructor); //function Function() { [native code] }alert(new Poker().constructor); //function Poker(style, title, value) {                                //            this.Style = style;                                //            this.Title = title;                                //            this.Value = value;                                //        }alert(Poker.constructor.prototype); //function Empty() {}alert(Poker.prototype == new Poker().constructor.prototype); // truealert(Poker.constructor.prototype == new Poker().constructor.prototype); // falsealert(new Poker().propertye); //undefined

The constructor of a function is a function object;

The constructor of the function (the object created by the function) is the definition of the function;

The prototype of the function constructor is an empty function;

The function prototype is equivalent to the constructor prototype of the object created by the function (so the object is constructed by the function );

The prototype of the constructor of a function is different from the prototype of the constructor of a function;

Objects without prototype can be directly accessed (this is the same as the word volume object );

The above text looks the same as the Tongue Twister, but you will understand it after reading more ......

To prove this, if you need a function member to access the instance, either add it to the function code or add it to the function prototype.

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.