Created
November 22, 2015 21:34
-
-
Save Teino1978-Corp/8e2a364096a4946e6e86 to your computer and use it in GitHub Desktop.
javascript: Chaining Pattern and Java-like Class method adding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Constants Construction | |
* @description 可以直接用全大寫的naming convention來模擬,此處實際建立一個指定常數的實作 | |
* @return {[type]} [description] | |
*/ | |
// Using naming convention directly | |
var Widget = function() { | |
// implement...... | |
}; | |
Widget.MAX_HEIGHT = 320; | |
Widget.MAX_WIDTH = 480; | |
// Implement constant() method | |
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] = values; | |
return true; | |
}, | |
isDefined: function(name) { | |
return ownProp.call(constants, prefix + name); | |
}, | |
get: function(name) { | |
if (this.isDefined(name)) { | |
return constants[prefix + name]; | |
} | |
return null; | |
} | |
}; | |
}()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Implementation of Java way method() function | |
* @description 每次都在實體上用this重新新增方法是沒效率的,可重用的方法應新增在建構式的prototype中 | |
*/ | |
// Use Constructor to define a "class" | |
var Person = function(name) { | |
this.name = name; | |
}.method('getName', function() { | |
return this.name; | |
}).method('setName', function(name) { | |
this.name = name; | |
return this; | |
}); | |
/** | |
* Implement method() | |
* @param { name } The name of the adding method | |
* @param { implementation } The implementation of the adding method | |
*/ | |
if (typeof Function.prototype.method !== 'function') { | |
Function.prototype.method = function(name, implementation) { | |
this.prototype[name] = implementation; | |
return this; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment