zoukankan      html  css  js  c++  java
  • JavaScript Patterns 5.9 method() Method

    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)

  • 相关阅读:
    数组_leetcode283
    数组_leetcode438
    数组_leetcode215
    数组_leetcode167
    数组_leetcode209
    数组_leetcode88
    数组_leetcode80
    数组_leetcode76
    数组_leetcode75
    数组_leetcode27
  • 原文地址:https://www.cnblogs.com/haokaibo/p/method-Method.html
Copyright © 2011-2022 走看看