0

Been trying to create a JavaScript object member that always contains a common string. Whenever I create a new object, instead of concatenating the string, it overwrites it with the passed value on creation. If it matters (I don't think it does) the string contains numbers. Par example:

function myObj(strToConcat){
    this.combinedString = "Hello " + strToConcat, /* have used + and .concat() without success */
}

var newObj = new myObj("1.2.3");
console.log(newObj.combinedString); /* says "1.2.3", the leading "Hello " is absent */

Can't seem to get this to concatenate the strings.

EDIT: I apologize, the error was outside the code that I thought responsible. Disregard please. My apologies.

1
  • Your example is pretty broken and does not output what you claim it to output. You have a syntax error and access the wrong variable. If you fix both it works: jsfiddle.net/CS2VD. No idea how you would get "1.2.3" though. Commented Mar 28, 2013 at 15:52

2 Answers 2

2

You have error in your reference

console.log(myObj.combinedString);

should be

console.log(newObj.combinedString);
Sign up to request clarification or add additional context in comments.

3 Comments

Argh, that's a typo. That's not what my code says. Sorry for misleading
also this is an error this.combinedString = "Hello " + strToConcat, - remove the comma at the end and put semicolon
If the OP really had console.log(myObj.combinedString); in their code, it would output undefined though, not "1.2.3". So, while this is a problem in the posted code, it's unlikely the problem for the OP's actual code.
1

Running your code gives me SyntaxError: Unexpected token }. Replace the , at the end of the second line with a ; and I get the expected result of "Hello 1.2.3".

2 Comments

If this error was in the OP's actual code, he would never get the output "1.2.3" though.
I know, we can only debug what is posted though. It would have been quite helpful if the actual code had been posted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.