JavaScript Patterns 5.9 method() Method
2014-07-04 13:11 小郝(Kaibo Hao) 阅读(400) 评论(0) 编辑 收藏 举报Advantage
Avoid re-created instance method to this inside of the constructor.
method() implementation
The method() takes two parameters:
• The name of the new method
• The implementation of the method
if (typeof Function.prototype.method !== "function") { Function.prototype.method = function (name, implementation) { this.prototype[name] = implementation; return this; }; }
How to use this pattern
var Person = function (name) { this.name = name; }.method('getName', function () { return this.name; }).method('setName', function (name) { this.name = name; return this; }); var a = new Person('Adam'); a.getName(); // 'Adam' a.setName('Eve').getName(); // 'Eve'
References:
JavaScript Patterns - by Stoyan Stefanov (O`Reilly)
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。