首页 > 网站 > WEB开发 > 正文

JavaScript Patterns 5.9 method() Method

2024-04-27 14:21:58
字体:
来源:转载
供稿:网友

javaScript Patterns 5.9 method() Method

2014-07-04 13:11 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑

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)


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表