简单的问题。我为什么要这样做...
var Person = function(name) {
this.name = name;
this.sayHello = function(){
console.log('Hello, my name is ' + this.name); // <--
}
};
而不是...
var Person = function(name) {
this.name = name;
this.sayHello = function(){
console.log('Hello, my name is ' + name); // <--
}
};
我还没有发现他们表现不同的情况。
最佳答案
因此,如果有任何函数重置名称,如果您不使用 this.name
,则不会反射(reflect)出来。检查这个例子
var Person = function(name) {
this.name = name;
this.sayHello = function() {
console.log('Hello, my name is ' + name);
console.log('Hello, my name is ' + this.name);// <--
}
};
Person.prototype.resetName = function(name) {
this.name = name;
}
var me = new Person('A');
me.sayHello();
console.log('******');
me.resetName('Ayan');
me.sayHello();
关于javascript - 为什么我应该在 Person Constructor(和类似的构造函数)中使用 `this.name` 而不是 `name`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38861905/