我試圖聲明一個對象函數,但似乎無法讓它工作。我不斷收到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錯誤。
您應該在'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
我得到對象#沒有方法'setOwner'。 –
其實我明白你的問題,你應該調用'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