2014-02-24 59 views
-1

我試圖聲明一個對象函數,但似乎無法讓它工作。我不斷收到Uncaught語法錯誤:意外的令牌。這發生在構造函數methodn的行中,嘗試定義我的方法。下面的代碼。無法爲JavaScript中的對象聲明函數

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錯誤。

+0

您應該在'Car'構造函數之外定義'Car.setOwner':function Car(make,model,year,owner){this.make = make; this.model = model; this.year = year; this.owner =擁有者; }; Car.setOwner = function(newOwner)this.owner = newOwner; }' – Marii

+0

我得到對象#沒有方法'setOwner'。 –

+0

其實我明白你的問題,你應該調用'c = new Car(...)'因爲'Car'是構造函數,所以這個例子實際上起作用:'函數Car(make,model,year,owner){ this。 make = make; this.model = model; this.year = year; this.owner =擁有者; this.setOwner = function(newOwner){this.owner = newOwner; } } undefined c = new Car('foo','bar',1954,'asdsa') Car {make:「foo」,model:「bar」,year:1954,owner:「asdsa」 ,setOwner:function} c.setOwner('Lala') undefined c.owner 「Lala」' – Marii

回答

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

您有:。要分配屬性,您需要使用=運算符。 :用於對象文字。

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

應該是:

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

當你聲明的對象的方法是需要的:

+0

我以爲我試圖聲明一個對象的方法嗎?除了我的錯誤語法,我誤解了什麼? –

+0

對不起,我的意思是當你這樣做時:'a = {b:function(){...}}' – Marii

+0

你能看到我的編輯結果並通過你的評論嗎? –