【问题标题】:Creating a Class and calling on it's properties (javascript)创建一个类并调用它的属性(javascript)
【发布时间】:2014-05-01 07:53:36
【问题描述】:

所以想法是创建一个类 Animal 并为其设置属性作为一个新对象

这是我所拥有的:

var name;
var type;
function Animal(name,type){
  this.type = type,
  this.name = name,
  toString = function(){return this.name + "is a " + this.type;}
};

var cat = new Animal('Max','cat');
cat.type;

每次我运行它 - 我似乎在 toString 部分失败了?很新,正在努力学习这个 - 我有什么遗漏吗?

【问题讨论】:

  • 你不需要声明那些顶级变量,参数应该是函数本地的。

标签: javascript class object


【解决方案1】:

您不需要声明那些顶级变量,参数应该是函数的本地变量。语法也是错误的,你应该使用分号,而不是逗号,并且toString变成了一个全局变量,因为你忘记了使用var

您想要的是this.toString,所以this 在内部工作并引用实例,或者更好的是,在prototype 上创建一个方法,以便它可重用于Animal 的所有实例:

function Animal(name,type) {
  this.type = type;
  this.name = name;
}

Animal.prototype.toString = function() {
  return this.name + "is a " + this.type;
};

【讨论】:

    【解决方案2】:
    function Animal(name, type) {
      this.type = type;
      this.name = name;
    };
    
    Animal.prototype.toString = function() {
      return this.name + "is a " + this.type;
    }
    
    var cat = new Animal('Max', 'cat');
    console.log(cat); // Prints "Max is a cat"
    

    【讨论】:

      猜你喜欢
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-24
      相关资源
      最近更新 更多