0

I created the following javascript object.

var obj = function () {
    var a = 6;
    var b = 7;
    var sumFunction;

    function sum() {
        alert(a);
        alert(b);
        sumFunction();
    }

    return {
        a: a,
        b: b,
        sum: function (f) {
            sumFunction = f;
            sum();
        }
    }
}

var o = new obj;

function Calculate() {
    o.a = 3;
    o.b = 4;

    o.sum(function () {
        alert('finish');
    });
}

When the Calculate method is called, the two alert box show 6 and 7. It should be 3 and 4. I don't know what wrong my object. How can I correct this? Thanks.

1
  • 1
    the reason why a and b are calling 6 and 7 is because you're not specifying this. it should be this.a, and this.b Commented May 10, 2014 at 10:31

2 Answers 2

1

First thing, you don't need to give a return value for functions used with new. Next, when you're refering to instance variables, you should use this.

var obj = function () {
    this.a = 6;
    this.b = 7;
    this.sumFunction;

    this.sum = function(f) {
        alert(this.a);
        alert(this.b);
        this.sumFunction = f;
        this.sumFunction();
    }


}



function Calculate() {
    var o = new obj;
    console.log(o);
    o.a = 3;
    o.b = 4;

    o.sum(function () {
        alert('finish');
    });
}
   Calculate();

example fiddle: http://jsfiddle.net/3WgKK/1/

Sign up to request clarification or add additional context in comments.

2 Comments

you don't need to give a return value for functions used with new - While your solution may work for the OP I would refrain from making such a generic assumption. It's a common pattern after all and for good reasons.
I don't think sumfunction should be a property of the object at all, it's just a callback.
1
function sum() {
  alert(a);

References the variable a, that still has the value 6. Your construct makes it somewhat difficult to reference the property a. The following approach does what you want:

function sum() {
    alert(this.a);
    alert(this.b);
    sumFunction();
}
    return {
    a: a,
    b: b,
    sum: function (f) {
        sumFunction = f;
        sum.call(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.