Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript why's this not working?

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #153005
    javascriptnewbie
    Participant

    okay = new Object{

    function=testing(){
    return 5+6;
    }

    }
    document.write(okay.testing());

    #153006
    Alen
    Participant
    var obj = {
        a: 5,
        b: 6,
        sum: function (a, b) {
            return this.a + this.b;
        }
    };
    
    alert(obj.sum()); // 11
    
    #153007
    Alen
    Participant

    You can also make this little bit modular:

    var CreateObject = function (a, b) {
        this.a = a;
        this.b = b;
    
        this.sum = function (a, b) {
            return this.a + this.b;
        };
        this.dif = function (a, b) {
            return this.a - this.b;
        };
    };
    
    var result1 = new CreateObject(5, 6);
    var result2 = new CreateObject(10, 34);
    var result3 = new CreateObject(34, 3);
    var result4 = new CreateObject(45, 300);
    //alert(result1.sum()); // 11
    //alert(result1.dif()); // -1
    //alert(result2.sum()); // 44
    //alert(result2.dif()); // -24
    //alert(result3.sum()); // 34
    //alert(result3.dif()); // 31
    //alert(result4.sum()); // 345
    //alert(result4.dif()); // -255
    
    #153008
    Alen
    Participant
    #153086
    Alen
    Participant

    @CrocoDillon That’s a great point, since the sum and dif get created each time, for each object… could just define them on the prototype… I didn’t want to go into memory management just yet.

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.