Javascript:何时何时不使用“this” [英] Javascript: When and when not to use "this"
问题描述
this
。我知道 this
用于确定函数 this
的值,但它总是需要吗? 我之所以问这个问题,是因为我有一个内部函数,它在我的模块中被调用,它真正做的就是对传递它的一些数据进行排序。我的问题是我应该使用这个
关键字来调用这个函数,或者单独使用。
例如:
function formatSomeData(data){
//代码........
}
this.formatSomeData(data);
或
formatSomeData(data);
我得到函数被调用的上下文以及它的目的在回答问题,但在这种情况下,就像我提到的那样,我真的不需要在任何时候访问 this
对象。在调用函数时使用它仍然是一个好习惯吗?
我所要求的并不是这个如何工作,而是什么时候适合使用它,何时不适合。
何时需要/最佳实践使用关键字this
当你想要访问某些内容时通常会使用它。所以举个例子,如果你有一个自定义对象,并且想要在某个方法中使用某个属性,你应该使用 this
。
function Person(fname,lname){this.fname = fname; this.lname = lname; this.fullName = function(){return this.fname +''+ this.lname; }} var p = new Person('foo','bar'); console.log(p.fullName())
如果您在当前构造函数中看到,我创建了一个函数( fullName
),它需要访问 fname
和 lname
属性是它所属的对象的属性。这是一个地方必须使用
。
现在声明时,何时使用
这个
?
构造函数中属于 this
的任何属性都将成为对象的一部分。所以如果你需要一些只能被你访问但不在外面的东西,你可以使用函数
而不是这个
。
至于你的代码,我已经在注释中解释了它的工作原理:
在非严格模式下,
这个
将指向窗口
和任何不在函数中的声明都将成为全局作用域的一部分。
Now while declaration, when to use
this
?
Any property in a constructor that is a part of this
will be a part of the object. So if you need something that is only accessible to you but not outside, you can use function
instead of this
.
function Person(fname, lname){
var self = this;
self.fname = fname;
self.lname = lname;
// This function is private
function getFullName() {
var name = '';
var seperator = '';
if (fname) {
name += self.fname;
seperator = ' ';
}
if (lname) {
name += seperator + self.lname;
}
return name;
}
this.fullName = function(){
return getFullName();
}
}
var p = new Person('foo', 'bar');
console.log(p.fullName())
As for your code, I have already explained in comment why it works:
In non-strict mode,
this
will point towindow
and any declaration not in a function will be a part of global scope.
But as rightly pointer by @Jonas W its a bad practice. Why it is bad?
- Any variable defined without declaration statement(
var|let|const
) will become part of global scope. - Any variable with declaration statement outside any functions will become part of global scope.
这篇关于Javascript:何时何时不使用“this”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!