JavaScript reinforcement tutorial-Introduction to object Creation Mode
This article mainly introduces the next article on Object creation mode. using various techniques, you can greatly avoid errors or write very simple code.
Mode: function syntax sugar
Function syntax sugar is an extension to quickly add a method (function) to an object. This mainly utilizes the prototype feature and the code is relatively simple. Let's first look at the implementation code:
If (typeof Function. prototype. method! = "Function") {Function. prototype. method = function (name, implementation) {this. prototype [name] = implementation; return this ;};} can be used to extend an object: var Person = function (name) {this. name = name ;}. method ('getname', function () {return this. name ;}). method ('setname', function (name) {this. name = name; return this;}); in this way, the getName and setName methods are added to the Person function. Next, let's verify the result: var a = new Person ('Adam '); conso Le. log (. getName (); // 'Adam 'console. log (. setName ('Eve '). getName (); // 'Eve 'mode 7: Object constant object constants are the embodiment of various methods provided by set, get, and ifDefined in an object, in addition, the set method only retains the first set object, and subsequent settings are invalid, so that others cannot reload the object. The implementation code is as follows: var constant = (function () {var constants ={}, ownProp = Object. prototype. hasOwnProperty, // only values of these three types can be set: allowed = {string: 1, number: 1, boolean: 1}, prefix = (Math. random () + "_"). slice (2); return {// set the property set: function (name, value) {if (this. isDefined (name) {return false;} if (! OwnProp. call (allowed, typeof value) {return false;} constants [prefix + name] = value; return true ;}, // determine whether the attribute isDefined with name exists: function (name) {return ownProp. call (constants, prefix + name) ;}, // get the property get: function (name) {if (this. isDefined (name) {return constants [prefix + name];} return null ;};} (); Verify the Code as follows: // check whether a console exists. log (constant. isDefined ("maxwidth"); // false // defines the console. log (constant. set ("maxwidth", 480); // true // re-detect the console. log (constant. isDefined ("maxwidth"); // true // try to redefine the console. log (constant. set ("maxwidth", 320); // false // determine whether the original definition still exists in the console. log (constant. get (& quot; maxwidth & quot;); // 480