无法在JavaScript中声明对象的函数

时间:2014-02-24 11:15:23

标签: javascript methods declaration

我试图声明一个对象函数,但似乎无法让它工作。我一直收到一个未捕获的语法错误:意外的令牌。这发生在构造函数methodn的行中,尝试定义我的方法。代码如下。

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner; 
  this.setOwner: function (newOwner){
            this.owner = newOwner;
    }
}


var AndrewsCar = new Car("Ford","Focus", 1999, "Andrew");
AndrewsCar.setOwner("Bobbie");
document.writeln(AndrewsCar.owner);

这个怎么样?我还可以声明这样的函数吗?

 Car.setOwner = function (newOwner){
            this.owner = newOwner;
}

我一直在尝试,当我尝试调用它时,我得到了一个TypeDef错误。

2 个答案:

答案 0 :(得分:1)

  this.setOwner = function (newOwner){
//              ^

你有:。要分配属性,您需要使用=运算符。 :用于对象文字。

答案 1 :(得分:0)

this.setOwner: function (newOwner){
            this.owner = newOwner;
    }

应该是:

this.setOwner = function (newOwner){
            this.owner = newOwner;
    }

声明对象的方法时需要: