问题描述
在此代码段中,为什么this.identifier
不起作用而_self.url
起作用?
In this code snippet, why is it that this.identifier
doesn't work but _self.url
works?
getConfig() {
let _self = this;
return function () {
this.page.url = this.url || window.location.href;
this.page.identifier = _self.identifier;
this.page.category_id = this.categoryId;
this.language = this.lang;
};
}
let _self = this
真的可以吗?
推荐答案
首先,您将获得投票,因为这根本不是一个愚蠢的问题.Stackoverflow上的某些人很容易获得奖励.
Firstly, you get an up vote as this is not a silly question at all.Some people on Stackoverflow are wayyyy to entitled.
函数具有称为上下文的内容.上下文是调用该函数的对象.
Functions has something called a context. A context is the object the function is being called on.
let person = {
name:"bill",
speak:function(){
console.log("hi i am "+this.name)
}
}
如果您要进行person.speak()
if you were to do person.speak()
它将在已定义的对象上调用.变量person
是上下文
it will be called on the object that was defined. The variable person
is the context
所以当你这么说的时候.这跟说出person.name一样
so when you say this. it's the same as saying person.name
现在,您可以将函数附加到其他对象上.
Now you can attach the function to something else.
var newperson = {name:'jill'}
newperson.speak = person.speak;
在被叫时我会吉尔这会打印出来.
this will print hi i am jill when it's called.
首先了解这一点.
现在进入第二步.
GetConfig返回一个函数,但是此函数未附加任何对象.
GetConfig returns a function, however this function is not attached any object.
检查一下.
let person = {
name:"bill",
getSpeakFunction:function(){
return function(){
console.log('hi my name is '+this.name)
}
}
}
let func = person.getSpeakFunction()
现在函数func完全由他自己承担.
Now the function func is all by himself.
现在,当被称为这个"的人是谁,你到底在说谁.这就是功能的想法.
Now when it is called who is "this" who the hell are you talking about.That is what the function is thinking.
所以我们可以通过说出帮助功能.
So we can help the function out by saying.
let person = {
name:"bill",
getSpeakFunction:function(){
let context = this; //listen hear function this is what i am talking about
return function(){
console.log('hi my name is '+context.name)
}
}
}
let func = person.getSpeakFunction()
此是一种特殊的语言,它由语言决定此值,而上下文则不是.上下文将是分配给它的任何内容.除非您由程序员进行更改,否则它不会更改.
this is special the language decides the value of this, however context is not.context will be whatever is assigned to it. It will not change unless you the programmer changes it.
因此使用单词_self,上下文$ this或其他,当您为其分配值时.像其他任何常规变量一样,它被锁定".
so using the word _self, context, $thisor anything else when you assign the value of this to it.it is 'locked in place' like any other regular variable.
let a = 2;
//this will never change
let _self = this //_self will never change as it's your variable
现在,当您调用函数时,它将查找_self.它完全知道您在说什么.
Now when you call your function and it looks for _self. it knows exactly what you are talking about.
ps.我也在寻求选票;)
ps. i am seeking votes as well ;)
这篇关于"let _self = this"是什么意思?在Javascript/Typescript中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!