0

I am new to constructor functions, and I have the following in a .js file I include:

// should just get the number of customers out of the passed-in object
function myCustomers(customerObj) {
    this.customerCount = function(customerObj) {
        return customerObj.length;
    };
}

On the .htm page which includes the .js file, I have the following:

var tmpObj = new myCustomers(custObj);
alert(tmpObj.customerCount);

What I expected was the alert to give me the number of customers, such as "1", etc. Instead, the alert contains the entire text of my function as though it were a string, like this:

function(customerObj) {
    return customerObj.length;
}

I'm sure this is simple, but I have had a tough time googling for an answer, since my search contains very generic words like function, text/string, method, etc. FYI, this example has been pared down from a more complicated function, to hopefully make it easier to understand the question. I have tested this simpler function with the same result.

Thanks in advance!

2 Answers 2

2

It looks like in your alert, you are not actually calling the function, but instead passing the function itself to alert(). Try this:

alert(tmpObj.customerCount(custObj));

You might also want to change your myCustomers object to hang on to the object that is passed into the constructor, so you don't have to pass it in again when you call the function.

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

1 Comment

Thank you, that answer both fixes my problem and explains why I was getting the function back as text. I appreciate the fast answer! As far as your advice, do you mean adding something like this.customers = custObj; in the constructor, then having my method return this.customer.length;?
2

You should call the method like this:

var tmpObj = new myCustomers(custObj);
alert(tmpObj.customerCount(custObj));

Note the method parenthesis ;)

1 Comment

Thank you MatuDuke... I see I incorrectly thought this.customerCount was the returned value of the method, instead of the method itself. Do I have that right? Thank you for the fast help!

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.