"JavaScript mode" study notes (5) - object creation mode 4

  We finished school most of the objects associated with content creation mode, there are some small but excellent section below.

 

Seven, object literal

  JavaScript has no notion of constant, although many modern programming environment may provide a const statements to create constants for you. As a workaround, JavaScript common method is to use a naming convention, so that those variables should not be modified in all capital letters to highlight. In fact, this naming convention has been used for the built-in JavaScript objects.

console.log(Math.PI);
console.log(Math.SQRT2);

  For your own constants, you can also use the same naming convention, and add them as static properties to the constructor.

// constructor 
var the Widget = function () {
     // achieve ... 
};

// constant 
Widget.MAX_HEIGHT = 320. ;
Widget.MAX_WIDTH = 480;

  The same naming conventions can be applied to an object literal creation, these constants can be in capital letters correctly named property.

  If you really want to have an immutable values, you can create a private property and provide a value (getter) method, but does not provide set-valued function (setter). However, in many cases, when a simple naming convention may adopt values, this function does not provide a set of methods may seem overkill.

  The following is a general Constant (constant) method object implementation example, it provides the following methods:

  set(name, value)

    Define a new constant.

  isDefined(name)

    Detect whether there is a fixed constant.

  get(name)

    Reading the value of the specified constant.

  In this implementation, only the original value (primitive value) is set to allow constant. In addition, some extra precautions to ensure that declared constants and built-in attribute names do not conflict, and other such toString or hasOwnProperty, you can add a prefix randomly generated name in front of all the constants by using hasOwnProperty () detects the name, and so ensure mutual adaptation between the name.

var constant = (function () {
    var constants = {},
        ownProp = Object.prototype.hasOwnProperty,
        allowed = {
            string:1,
            number:1,
            boolean:1
        },
        prefix = (Math.random() + "_").slice(2);
    
    return {
        set:function(name,value) {
            if(this.isDefined(name)) {
                return false;
            }
            if(!ownProp.call(allowed,typeof value)){
                return false;
            }
            constants[prefix + name] = value;
            return true;
        },
        isDefined:function(name) {
            return ownProp.call(constants,prefix + name);
        },
        get:function(name) {
            if(this.isDefined(name)){
                return constants[prefix + name];
            }
            return null;
        }
    }
}());

// test the above code that implements 
// Check if you have defined 
constant.isDefined ( "maxwidth" );

// define 
constant.set ( 'maxWidth', 480 );

// check again 
constant.isDefined ( 'maxWidth' );

// attempt to redefine 
constant.set ( "maxwidth", 320 );

// if the value remains unchanged throw 
constant.get ( "maxwidth");

  

Eight, chain model

  Chain model (Chaining Pattern) allows you to call one after object method, without a preceding value of the operation returns to the variable, and need not take your call divided into a plurality of rows:

myobj.method1("hello").method2().method3("world").method4();

  When the method is to create a return without any sense of value, so that they can return to this, an example of an object that is being used. This makes the object's user invokes the next method front connections:

There obj = {
    value:1,
    increment: function () {
        this.value += 1;
        return this;
    },
    add: function(v) {
        this.value += v;
        return this;
    },
    shout:function () {
        alert(this.value);
    }
};

// chain method calls 
obj.increment () add (3) .shout ().;

  

Advantages and disadvantages of the chain model

  One advantage of using chain model that can save some of the character input, and can also create a more concise code, so that it reads like a sentence.

  Another advantage is that it can help you consider the partition function to create a more brief, with specific functions function, rather than trying to achieve too many features to create a function. In the long term, this improves the maintainability of the code.

  One drawback is that the chain code pattern written in this manner is more difficult to debug. Perhaps until an error occurs in a particular line of code, but the actual implementation in this line too many steps. When a method wherein a plurality of chain muting fails, which is not until the method fails.

  In any case, we recognize that this mode very good. When the method of preparation and no significant and meaningful return value, you can always return to this. The model has been widely used, such as jQuery library on the use of this mode. In addition, if you look at the DOM API, then it can also be noted that the structure also tends chain.

 

Nine, method () method

  JavaScript programmers who might use in a class way of thinking confused. This is why some developers prefer to make JavaScript more similar class. One such attempt is thought Douglas Crockford introduced method () method. In retrospect, he admitted that the idea of ​​a similar class JavaScript is not recommendable program, but it is still a cause for concern mode, it is possible to come across this model in some applications.

  Use the constructor looks like in use in Java classes. They also support that you add to an instance attribute constructor body of this. This mechanism is then added to this method is actually very inefficient, because they will eventually be re-created with each instance, and consumes more memory space. This is why the method should be added to the reasons for taking the prototype property of the constructor.

  Adding to the convenience of programming language functions are also known as syntactic sugar. In this case, method () method can also be called "sugar method (sugar method)".

  Using method () of the method defined in the following classes:

var Person = function (name) {
    this.name = name;
}.
    method('getName',function() {
        return this.name
    }).
    method('setName',function(name) {
        this.name = name;
        return this;
    })

  Please note that the constructor is how to connect to method () call, which in turn is connected to the next method () calls back and so on. This example follows the chain model described earlier, it can help you in a single declaration statement defines the entire "class."

  method () method takes two parameters: the name of the new method, the implementation of the method.

var a = new Person('Adam');
a.getName();
a.setName ( 'Eve' ) .getName ();
 // Again, note chain model is already in force, because setName () returns this, so that the above code can be run properly.

// Finally, we look at the method () method is how to achieve:

if(typeof Function.prototype.metho !== 'function') {
    Function.prototype.method = function (name,implementation) {
        this.prototype[name] = implementation;
        return this;
    };
}

  In the implementation method (), first we should carefully check whether the method has been achieved before. If not, then continue to add functions, and passed to the constructor as a prototype implementation parameters. In this case, it refers to the this constructor, the prototype has been enhanced.

 

  Object content creation mode here came to an end, the article explained the whole chapter namespace mode, declare a dependency, a series of useful methods to create objects of private mode, the module mode and sandbox mode, object literal chain mode . So the next chapter, we will learn next code reuse mode. Oh, very important.

Guess you like

Origin www.cnblogs.com/zaking/p/12622341.html