如何检查javascript的构造
我有一个函数fn(),它重新定义了这个关键字,请参见下文如何检查javascript的构造,javascript,this,Javascript,This,我有一个函数fn(),它重新定义了这个关键字,请参见下文 function fn() { return this; } log( fn() === function, "The context is the global object." ); //ERROR Unexpected token log( fn() === this, "The context is the global object." ); //true 我有一个问题fn()==函数为什么它不是真的??fn()和函数的
function fn()
{
return this;
}
log( fn() === function, "The context is the global object." );
//ERROR Unexpected token
log( fn() === this, "The context is the global object." );
//true
我有一个问题fn()==函数为什么它不是真的??fn()和函数的类型相同
这是真的吗??而fn()和this不是同一类型
如果我这样做
function fn(){
//return this;
}
那么结果是假的。这意味着fn()==此条件正在将其与fn()返回进行比较。您可能需要检查
typeof
function fn() {
return this;
}
console.log((typeof (fn) == "function"), "The context is the global object.");
// true, "The context is the global object."
console.log(fn() === this, "The context is the global object.");
// true "The context is the global object."
所以
fn()=“函数”-->false
。因为fn()
fn()===this-->true
,因为this
(函数的所有者,即window
)和全局对象this(window)
是相等的如果要确定类型,请尝试typeof运算符
console.log( typeof(fn) === 'function' ? 'Its a function' : 'Its NOT a function' );
据我所知,从fn()返回的“this”是一个窗口对象,而不是函数。@user13500 yup
typeof
返回string@Pilot-这不是,这是一个问题。如果调用未设置函数的this关键字,则默认为全局对象。如果不是在严格模式下设置,它将是未定义的。@RobG 100%同意,但这取决于上下文well@Pilot-这是执行上下文的一个参数,它本身不是任何意义上的“上下文”。这是全局对象(作为windows实现)。所以比较this==this
无论如何都会得到true
function fn()
{
return this;
}
console.log((fn() === function));
// the output of function is trying to be compared with the function
// declaration... you can't do that... you need to compare against a value
console.log((typeof fn === 'function'));
// the type of fn itself, not its return value, is the string 'function',
// therefore it is true
console.log((fn() === this));
//the return value of the function is this... this is the window object and
// this exists, therefore this is true