如何从构造函数调用对象的方法?

时间:2010-04-15 10:10:36

标签: javascript oop

var Dog = function(name){       this.name = name;       this.sayName();     }

Dog.prototype.sayName = function() {
  alert(this.name);
}

我正在创建Dog对象Dog('Bowwow')的新实例,但方法sayName()未定义。为什么呢?

或许我应该做点什么(但我看不出差异)......

var Dog = function(name) {

  this.name = name;

  this.sayName();

  this.prototype.sayName = function() {
    alert(this.name);
  }
}

谢谢。

1 个答案:

答案 0 :(得分:5)

JavaScript在这方面有点狡猾,只要您使用new构造函数调用Dog,您的代码就会起作用。

new Dog("Hello world")

新的构造函数使this的行为与您想要的一样。否则就完全不同了。

相关问题