书中的例子出错 - "意外的令牌{"

Kud*_*aev 1 javascript

我正在读一本关于JavaScript的书(最近开始学习).在运行书中的一个示例时,我收到错误.我在Ubuntu上使用Chromium浏览器,14.0.835.202.

由于我是新手,我无法理解为什么会有错误.提前致谢.

Function.prototype.method = function (name, fn)
{
    this.prototype[name] = fn;
    return this;
};


var Person
{
    this.name = name;
    this.age = age;
};


Person.
    method ("getName", function
    { // error here - "Uncaught SyntaxError: Unexpected token {"
        return this.name;
    }).
    method ("getAge", function
    {
        return this.age;
    });


var alice = new Person ("Alice", 93);
var bill = new Person ("Bill", 30);

Person.
    method ("getGreeting", function
    {
        return "Hi" + this.getName() + "!";
    });

alert (alice.getGreeting());
Run Code Online (Sandbox Code Playgroud)

编辑:

解决方案给了我另一个我想问的问题.对于对象声明:

var Object = function (...) // line 1
{
    // code here
};
Run Code Online (Sandbox Code Playgroud)

如果变量的数量太大以至于我不想在第1行列出它们,我该怎么办?

Sir*_*rko 5

你在这里错过了=(很可能function也是):

var Person = function( name, age ){
    this.name = name;
    this.age = age;
};
Run Code Online (Sandbox Code Playgroud)

同样,稍后你的函数定义中缺少一些括号,例如:

method ("getName", function()
    {
        return this.name;
    }).
Run Code Online (Sandbox Code Playgroud)

  • 应该还是错的.应该是`姓名:姓名,年龄:年龄`,不是吗? (2认同)