After reading about prototype in JavaScript, I've created this JSFiddle to test some things about how functions work.
I understand that the prototype of the two functions are not the same. But why are the 'foo' and 'bar' functions the same as they have a different name and they both do different things?
The code:
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 Answers 4
foo and bar are functions that exist inside the function bodies of test1 and test2 when they are executing.
They are not properties of test1 and test2 and so, test1.foo and test2.bar are both undefined.
Comments
Because both, test1.foo and test2.bar values are undefined. You can see them by outputting like console.log(test1.foo) and console.log(test2.bar)
I suggest you to output any parameter with which you're going to make a comparison in order to see the differences and guess what's going wrong.
Comments
in expression test1.foo === test2.bar, they are both undefined,
you create property of object in wrong way,
check "javascript: the definitive guide 6th" for how to do this.
Comments
Both of them return undefined since there is no property called foo and bar and so undefined == undefined becomes true, which is why you are getting the alert alert("they're the same");
test1.foo()?undefined.undefined.