Grow your CSS skills. Land your dream job.

why's this not working?

  • # October 14, 2013 at 2:11 pm

    okay = new Object{

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

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

    # October 14, 2013 at 3:47 pm
    var obj = {
        a: 5,
        b: 6,
        sum: function (a, b) {
            return this.a + this.b;
        }
    };
    
    alert(obj.sum()); // 11
    
    # October 14, 2013 at 3:59 pm

    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
    
    # October 14, 2013 at 4:00 pm

    http://jsfiddle.net/fWwbe/

    # October 15, 2013 at 5:22 am

    Alen, your functions don’t need to take parameters since you take it off the object created with new CreateObject(...). If you go object oriented it’s better to add the functions to the CreateObject.prototype object to avoid wasting memory (now each object has those functions defined).

    Go to http://www.objectplayground.com/ and compare this:

    var CreateObject = function (a, b) {
        this.a = a;
        this.b = b;
    
        this.sum = function () {
            return this.a + this.b;
        };
        this.dif = function () {
            return this.a - this.b;
        };
    };
    
    this.result1 = new CreateObject(5, 6);
    this.result2 = new CreateObject(10, 34);
    

    to this:

    var CreateObject = function (a, b) {
        this.a = a;
        this.b = b;
    };
    CreateObject.prototype.sum = function () {
        return this.a + this.b;
    };
    CreateObject.prototype.dif = function () {
        return this.a - this.b;
    };
    
    this.result1 = new CreateObject(5, 6);
    this.result2 = new CreateObject(10, 34);
    

    To TS:

    var okay = {
        testing: function(){
            return 5+6;
        }
    };
    
    document.write(okay.testing());
    
    # October 15, 2013 at 11:55 am

    @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 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".