JavaScript函数和原型

JavaScript函数和原型,javascript,Javascript,在阅读了JavaScript中的prototype之后,我创建了它来测试函数如何工作 我知道这两个函数的原型是不一样的。但是为什么“foo”和“bar”函数是相同的,因为它们有不同的名称,并且它们都做不同的事情 守则: var test1 = function(){ function foo(){ alert('test1 foo function'); } } var test2 = function(){ function bar(){ alert('tes

在阅读了JavaScript中的prototype之后,我创建了它来测试函数如何工作

我知道这两个函数的原型是不一样的。但是为什么“foo”和“bar”函数是相同的,因为它们有不同的名称,并且它们都做不同的事情

守则:

var test1 = function(){
function foo(){
    alert('test1 foo function');
}
}

var test2 = function(){
    function bar(){
        alert('test2 foo function');
    }
}

if (test1.foo === test2.bar) {
    alert("they're the same")
}

if (test1.prototype === test2.prototype){
    alert("they're not the same")
}

因为,
test1.foo
test2.bar
值都是
未定义的
。您可以通过输出
console.log(test1.foo)
console.log(test2.bar)


我建议您输出要与之进行比较的任何参数,以便查看差异并猜测出问题所在。

在expression
test1.foo===test2.bar
中,它们都未定义,
您以错误的方式创建对象的属性,

查看“javascript:第6版明确指南”了解如何执行此操作。
foo
bar
是执行时存在于
test1
test2
函数体内的函数


它们不是
test1
test2
的属性,因此,
test1.foo
test2.bar
都是
undefined
它们都返回
undefined
,因为没有名为
foo
bar
的属性,因此
undefined==undefined
变为真,这就是为什么您会收到警报
警报(“它们是一样的”)

您是否尝试调用
test1.foo()
?您似乎对函数范围感到困惑,函数中的变量无法通过这种方式访问。两者都是
未定义的
@deceze:这没有任何影响,它们都将返回
未定义的
@OneKitten正是我的观点。