Javascript库模板

时间:2015-10-15 11:51:56

标签: javascript oop constructor scope prototype

假设我需要像这样创建一个javascript库:

;(function(){

    var root = this;

    var Ctor = function(value) {
        this.value = value;
    };

    var _ = new Ctor(value);

    _.doSome = function(value) {
        // do some work to the value
        // if no value assigned, get the value of the previous method
    };

   _.doSome2 = function(value) {
        // do some work to the value
        // if no value assigned, get the value of the previous method
    };

   _.doSome3 = function(value) {
        // do some work to the value
        // if no value assigned, get the value of the previous method
    };

   root._ = _;

}.call(this));

如果doSome方法可以处理_对象的值,也可以使用doSome2和doSome3。

但是如何将这些方法链接起来呢:

// the doSome2 and doSome3 work with the value of doSome
_.doSome(value).doSome2().doSome3();

// the doSome3 work with the value of doSome2 cuz it has a value
_.doSome(value).doSome2(value).doSome3();

// every method work with the value assigned to it
_.doSome(value).doSome2(value).doSome3(value); // the same as:
_.doSome(value);
_.doSome2(value);
_.doSome3(value);

注意:方法可以随机链接,例如:

_.doSome2(value).doSome().doSome3();

实例:https://jsbin.com/vijehotora/edit?js,console

1 个答案:

答案 0 :(得分:1)

你可以这样做:

var Ctor = function() {};

Ctor.prototype = {
    doSome: function(value) {
        if(value) {
            this.value = value;
        }

        return this;
    },

    doSome2: function(value) {
        if(value) {
            this.value = value;
        }

        return this;
    }    
};

new Ctor().doSome('value1').doSome2('value2').doSome();

Working example