为什么这行Javascript代码出错?

Dou*_*auf 0 javascript

这行代码中有一个代码

 Boo.prototype.initone (a) { <-- Syntax error
Run Code Online (Sandbox Code Playgroud)

我想用一个属性this.bar创建一个Boo的简单对象,为什么这会给我一个错误?下面列出了错误,这是一个未被捕获的语法错误,但我没有看到它.

我知道不应该发布语法错误,但我只是没有看到下面这段代码的完全错误.

错误代码在这里:

 Boo.prototype.initone (a) {
     this.bar = a;
     return this;
 }
Run Code Online (Sandbox Code Playgroud)

错误

 Uncaught SyntaxError: Unexpected token { 
Run Code Online (Sandbox Code Playgroud)

码:

<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>
Run Code Online (Sandbox Code Playgroud)

代码:此代码仍将显示未捕获的异常.如果我把这个返回,那么initone上不会出现错误,但inittwo似乎没问题.

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

Boo.prototype.inittwo = function (b) {
    this.bar = 'something to do with ' + b;
    return this;
}
Run Code Online (Sandbox Code Playgroud)

Sea*_*lsh 5

你在这里得到一个语法错误,因为JavaScript不知道是什么,你想做的事.如果要定义函数,则需要使用function关键字指定它.

在这种情况下,它需要写为:

Boo.prototype.initone = function(a) {
    this.bar = a;
    return this;
}
Run Code Online (Sandbox Code Playgroud)

您还需要对方法进行更改inittwo.