JavaScript函数和原型

时间:2014-04-18 07:37:18

标签: javascript

在阅读了JavaScript中的原型之后,我创建了这个JSFiddle来测试一些关于函数如何工作的东西。

据我所知,这两个功能的原型并不相同。但是为什么'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")
}

4 个答案:

答案 0 :(得分:2)

foobar是执行时test1test2的函数体中 内部的函数。

它们不是test1test2的属性,因此,test1.footest2.bar都是undefined

答案 1 :(得分:1)

因为test1.footest2.bar值都是undefined。您可以通过输出console.log(test1.foo)console.log(test2.bar)

来查看它们

我建议您输出您要进行比较的任何参数,以便查看差异并猜出出现了什么问题。

答案 2 :(得分:0)

表达式test1.foo === test2.bar中的

,它们都是未定义的,
你以错误的方式创造对象的属性,
检查“ javascript:最终指南6th ”,了解如何执行此操作。

答案 3 :(得分:0)

它们都返回undefined,因为没有名为foobar的属性,所以undefined == undefined变为真,这就是你获得警报的原因{{1 }}