在Function对象上扩展method方法

;(function() {
    /**
     * 在Function对象上扩展method方法
     * @param  {String}   name     扩展的方法名称
     * @param  {Function} callback 方法的定义
     * @return {Function} return this  提供链式调用
     */
    if(typeof Function.prototype.method !== 'function'){
        Function.prototype.method = function(name, callback) {
            // 在当前function上扩展name方法
            this.prototype[name] = callback;
            // 便于method方法的链式调用
            return this
        }
    }

    // method方法的运用
    var Hoogle = function() {
            this.name = "Hoogle", 
            this.major = "F2E"
        };

    // 扩展hoogle构造函数上的原型方法
    Hoogle.method("getName", function() {
        return this.name
    }).method("setName", function(newname) {
        this.name = newname;
        return this
    }).method("getMajor", function() {
        return this.major
    }).method("setMajor", function(newmajor) {
        this.major = newmajor;
        return this
    });

    // 实例化Hoogle
    var hoogle = new Hoogle();
    // 设置静态属性并输出结果
    hoogle.setName("newHoogle").setMajor("newMajor");
    console.info(hoogle.getName(), hoogle.getMajor());

})();

 

转载于:https://www.cnblogs.com/qianduanjingying/p/5531880.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值