【发布时间】: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