4

I have been trying to find a way to chain these methods together in a similar way to jQuery. here is an example of what I mean:

(function() {
    window.foo = function foo( id ) {
        if( window == this )
            return new foo( document.getElementById( id ) );

        this.alert = function() {
            alert( object.value ); 
        }
    }
}());

foo('input').alert();

So as you can see, I would like to use the object that was passed into the class as part of the alert function, but I do not want to store it in the class via this.object = id, and then do alert( this.object.value );

What would be an elegant way to go about this?

1

2 Answers 2

4

jQuery only chains by returning the same jQuery object from many of its methods. Your method doesn't always return a value, so it won't chain reliably. If you always have it return a value of the same type, chaining may begin to make sense.

window.foo = function foo( id ) {
    if( window === this )
        return new foo( document.getElementById( id ) );
    this.alert = function() {
        if (this.value) alert( this.value ); 
    }
    return this;
}

foo('input').alert();
Sign up to request clarification or add additional context in comments.

Comments

-1

You don't need to store a reference in the object, because you already have it as id.

this.alert = function() {
    alert(id.value);
    return this;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.