【问题标题】:Why is it recommended to include methods inside the constructor ? - Javascript为什么建议在构造函数中包含方法? - Javascript
【发布时间】:2014-02-09 05:19:18
【问题描述】:

我目前正在阅读一本关于 Javascript 的书,作者建议在构造函数中声明方法,而不是将它们放在构造函数之外。 (我不是指“PROTOTYPE”关键字)

推荐方法

    function User(uname,password){
    this.uname=uname;
    this.password=password

    this.displayUser=function(){ // inside the constructor 
    document.write(this.uname+this.password);
};
}

替代方法

function user(uname,password){
   this.uname=uname;
this.password=password;

}
function displayUser(){ // outside the constructor 
document.write(this.uname+this.password);
}

谁能解释我为什么作者推荐方法1。以这种方式声明它有什么好处还是最佳实践?

【问题讨论】:

  • 第二种方法非常错误。
  • 从技术上讲,方法 1 是您的做法。在第一个代码中您创建了一个方法,在第二个代码中只是一个函数,如果您使用适当的上下文调用它,您可以将其变成一个方法。
  • @thefourtheye - 为什么你说方法 2 非常错误?
  • 因为它不等同于第一个代码。在这种情况下你会怎么称呼displayUser
  • @FelixKling - 是的,非常正确。我刚试过你在netbeans上说的。我创建了一个实例并尝试使用 . (点)运算符。方法甚至没有加载,但它适用于方法1。

标签: javascript function methods constructor


【解决方案1】:

在第一个代码中,您有一个带有两个属性(uname、密码)和一个方法(displayUser)的构造函数。 this 是指使用new 关键字创建实例时的实例:

var user = new User('Joe', 'abc123');
user.displayUser();

在第二个代码中,您的构造函数具有两个属性,但没有方法。通过将displayUser 创建为普通函数,而不是绑定到this,您的实例和方法之间会断开连接,您不能再调用user.displayUser()。但在 JavaScript 中,一切都是动态的,如果您显式传递上下文,您可以调用 displayUser

var user = new User('Joe', 'abc123');
displayUser.call(user); // `this` is `user`

另一种常见的方法是将方法添加到原型中,而不是添加到每个新实例中,而是在实例之间共享:

function User(uname,password){
  this.uname = uname;
  this.password = password;
}

User.prototype.displayUser = function() {
  ...
};

所有这些方法都是有效的,但最后一种是最常用的,并且比第一种具有最好的性能。第二个只是不方便,大多数时候。

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 2021-01-08
    • 2016-08-11
    • 2016-07-17
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多