-2

There is a code that on this line of code

 Boo.prototype.initone (a) { <-- Syntax error

I want to create a simple object of Boo with one property this.bar why would this be giving me an error? The error is listed below which is an uncaught Syntax Error but I am not seeing it.

I know that syntax errors should not be posted but I am just not seeing what is completely wrong with this code below.

Error Code Here:

 Boo.prototype.initone (a) {
     this.bar = a;
     return this;
 }

Error

 Uncaught SyntaxError: Unexpected token { 

Code:

<script>
function Test1() {
}

function Boo () {
    this.bar = 'Test This Method';
}

Boo.prototype.initone (a) {
    this.bar = a;
    return this;
}

Boo.prototype.inittwo (b) {
    this.bar = 'something to do with ' + b;
    return this;
}

var a = new Boo().initone('constructor 1');
var b = new Boo().inittwo('constructor 2');
</script>

Code: This code will still show an uncaught exception. If I take the return this out then no error will occur on initone but inittwo seems to be ok.

Boo.prototype.initone = function (a) {
    this.bar = a;
    return this;
}

Boo.prototype.inittwo = function (b) {
    this.bar = 'something to do with ' + b;
    return this;
}
5
  • 4
    Make it Boo.prototype.initone = function(a) { Commented Jul 7, 2014 at 2:23
  • 2
    What made you think that Boo.prototype.initone (a) { } would define a function? Commented Jul 7, 2014 at 2:25
  • 2
    Your updated code will not throw a SyntaxError. If it does, then there's some other problem outside that code. Or is it a different error? If you're in strict mode, it's possible for the value of this to be null or undefined, which would result in a TypeError. Commented Jul 7, 2014 at 3:22
  • 1
    ...the return certainly won't be a SyntaxError. Commented Jul 7, 2014 at 3:24
  • The code in your question runs with no exceptions (fiddle). If you're still getting errors, we need to see more of the code. Commented Jul 7, 2014 at 4:46

2 Answers 2

5

You're getting a syntax error here because JavaScript doesn't know what you want to do. If you're defining a function, you need to specify it with the function keyword.

In this case, it needs to be written as:

Boo.prototype.initone = function(a) {
    this.bar = a;
    return this;
}

You'll also need to make the change on your inittwo method.

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

Comments

3

Because that's not how you define a function on an object in JS :)

You have to use an equals sign:

Foo.prototype.initone = function(bar){
}

I think you are remembering the syntax for defining a function like so:

function f() { }

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.