Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Apr 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Smile Nested Methods and Properties in JavaScript

    Hi all! I'm pretty new to JavaScript and completely new to this forum. I'm James.

    Well uh, I'm not sure how to...

    I wanted to make something like this using javascript...

    Code:
    myObject.someMethod('something').anotherProperty
    much like the

    Code:
    document.getElementById('someId').style.morestuff
    But the thing is, I've been around every DOM whatnot I can find, I just can't seem to make it work.

    I kinda need it to make my own DOM for some API i'm writing. So I can write like...

    Code:
    function someGreatAPI(){
         this.property1='';
         this.property2='';
         //...
         this.method1 = function(var1){            //this should make my firstMethod
               this.nestedProperty = 0;
               this.nestedMethod = someFunction;  //firstMethods nested method
    
         }
    }
    
    //so I can use it like...
    
    var obj = new someGreatAPI();
    obj.method1(10).nestedMethod();
    It has to be possible, it's possible with document.getelementbyid, right? it has to be.

    Thanks in advance.
    Last edited by jschrend; 04-26-2010 at 11:07 PM. Reason: Solved!

  • #2
    Regular Coder
    Join Date
    Jan 2006
    Posts
    568
    Thanks
    6
    Thanked 84 Times in 84 Posts
    The reason it works with document.getElementById is because getElementById returns an HTML element.

    obj.method1 doesn't return anything, so obj.method1(10).nestedMethod() is resolved as obj.(undefined).nestedMethod()

    Since method1 is a constructor, you would do it like this:

    Code:
    var testObj=new obj.method1(10);
    testObj.nestedMethod();
    Edit - to make it work in exactly the same way you would have to do something like this:

    Code:
    function someGreatAPI(){
    	this.property1='';
    	this.property2='';
    	//...
    	
    	this.method1 = function(var1) {
    		this.nestedProperty = 0;
    		this.nestedMethod = function() {
    			alert(var1);
    		};
    	}
    	
    	this.createNewM1=function(n) {
    		return new this.method1(n);
    	}
    }
    
    var obj = new someGreatAPI();
    
    obj.createNewM1(10).nestedMethod();
    Last edited by gusblake; 04-26-2010 at 09:43 PM.

  • #3
    New to the CF scene
    Join Date
    Apr 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts


    It has to return an object, I see. Thanks man, that's exactly what I needed.







  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •