Javascript 这是java脚本中的作用域
我知道Javascript 这是java脚本中的作用域,javascript,class,this,Javascript,Class,This,我知道这个关键字是根据调用函数的方式来计算的。我有以下代码: name='sohan'; income=23232; class Person{ constructor(name,income) { this.name=name; this.income=income; } print(){ console.log(this.name); console.log(this.income); }
这个
关键字是根据调用函数的方式来计算的。我有以下代码:
name='sohan';
income=23232;
class Person{
constructor(name,income)
{
this.name=name;
this.income=income;
}
print(){
console.log(this.name);
console.log(this.income);
}
getFunc(){
return this.print;
}
}
let p1=new Person('bhavuk',10000);
let print=p1.getFunc();
print();
我怀疑
print()
是否应该将其与全局上下文绑定。我希望是“sohan 23232”,但它给出了错误名称未定义
。请解释一下这是怎么回事。谢谢。当您全局初始化变量name
和income
而不使用let
,const
或var
时,它们在非严格模式下隐式成为全局对象的属性
现在在类Person
中定义了方法print
。在严格模式下隐式运行的类,当您从类实例获取方法引用时,此
将始终是未定义的
:
let print=p1.getFunc()代码>
在上面的代码段中,方法引用保存在print
变量中,但是print
函数中的this
由于严格模式而未定义。因此,当您运行print
时,它将抛出一个错误
发件人:
当调用静态或原型方法时,没有该方法的值,
例如,通过向方法分配一个变量,然后调用它
此值将在方法中未定义。这种行为将被禁止
即使“use strict”指令不存在,也是一样的,因为
类主体语法边界内的代码始终以
严格模式
为了将此
指向预期对象,您可以使用Function.prototype.bind
将预期的此
绑定到方法引用:
name='sohan';
收入=23232;
班主任{
建造商(姓名、收入)
{
this.name=name;
这个。收入=收入;
}
打印(){
console.log(this.name);
console.log(这是收入);
}
getFunc(){
返回此文件。打印;
}
}
设p1=新人('bhavuk',10000);
设myPrint=p1.getFunc();
myPrint=myPrint.bind(p1);
myPrint();
//将冲击到声明2个属性的全局对象
myPrint=p1.getFunc();
myPrint=myPrint.bind(globalThis);
myPrint();
//将抛出错误,因为未定义this
myPrint=p1.getFunc();
myPrint()代码>类在严格模式下运行,因此未指定的this
将是未定义的(它不会像在对象文本中那样默认为全局对象(在浏览器窗口中)。@Reyno如果我们想回答,我建议返回这个.print.bind(这个)代码>在getFunc()
中。不,链接中的输出是我所期望的。我的代码与你的链接所建议的不同。@tevemadar是的,我正要更改我的评论,但你抢先一步!尼克用略微不同的词来表达:在严格模式下,“正常”函数调用中的这个是未定义的。