【问题标题】:Cant declare a function for an object in JavaScript无法在 JavaScript 中为对象声明函数
【发布时间】:2014-02-24 11:15:23
【问题描述】:

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

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.setOwnerfunction Car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; }; Car.setOwner = function (newOwner){ this.owner = newOwner; }
  • 我得到 Object# 没有方法 'setOwner'。
  • 其实我理解你的问题,你应该调用c = new Car(...),因为Car是构造函数,所以这个例子确实有效: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; } } 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"

标签: javascript methods declaration


【解决方案1】:
  this.setOwner = function (newOwner){
//              ^

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

【讨论】:

    【解决方案2】:
    this.setOwner: function (newOwner){
                this.owner = newOwner;
        }
    

    应该是:

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

    声明对象的方法时需要:

    【讨论】:

    • 我以为我试图声明一个对象的方法?除了我不正确的语法外,我误解了什么?
    • 对不起,我的意思是当你这样做时:a = { b: function() { ... } }
    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2012-04-04
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2019-02-27
    相关资源
    最近更新 更多