开发者

Object Oriented Programming in Javascript

开发者 https://www.devze.com 2023-01-30 10:19 出处:网络
Consider an OOP model. I wanted to implement, funct1( arg ).subfunct1( arg ); ( Of course like jQuery. where you have $( arg )开发者_C百科.subfn( arg )

Consider an OOP model. I wanted to implement,

funct1( arg ).subfunct1( arg ); ( 

Of course like jQuery. where you have $( arg )开发者_C百科.subfn( arg )

I have done it successfully for one subfunction. BUT,

funct1( arg ).subfunct1( arg ); // ==> works fine.
funct1( arg ).subfunct1( arg ).subfunct( arg ); // ==> doesnt work.

Source is:

var funct1=function() { 
    var dummy=new Object(); 
    dummy.subfunct1=bla bla; 
    dummy.subfunct2=bla bla; 
    return dummy; 
}

Can you say any remedies.


subfunct1 has to return this in order to have chainable calls.


That only works in jQuery, because most functions are setup to return the jQuery object that they are a part of (this), after modification, so that they can be chained together.

What do your functions return?


There's a method to enable chainable calls on any object without return this:

function chain(obj) {
    return function() {
        var Self = arguments.callee; Self.obj = obj;
        if(arguments.length==0) return Self.obj;
        Self.obj[arguments[0]].apply(Self.obj,[].slice.call(arguments,1));
        return Self;
    }
}

Usage:

function ClassA() {
    this.prop1 = null;
    this.prop2 = null;
    this.prop3 = null;
}

ClassA.prototype = {
    method1: function(argu) {this.prop1 = argu;},
    method2: function(argu) {this.prop2 = argu;},
    method3: function(argu) {this.prop3 = argu;}
}

var a = new ClassA();
chain(a)('method1',4)('method2',5)('method3',6)();

ref: http://www.javaeye.com/topic/748348 (in Chinese)


Thanks for suggestions :), btw I tried a few hours as I'm not conceptually strong and got an working procedure as follows..

var funct1=function() { 
    var dummy=new Object(); 
    var clone=dummy;
    dummy.subfunct1=bla bla; //you have to return every time the clone object 
    dummy.subfunct2=bla bla; //you have to return every time the clone object 
    return dummy; 
}

thus the function (anyway) become chained to n times.
Hope this helps anyone who searches as me :)

0

精彩评论

暂无评论...
验证码 换一张
取 消