1

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")
}
5
  • Have you tried calling test1.foo()? Commented Apr 18, 2014 at 7:40
  • You seemed to be confused about function scope, variables within a function are not accessible that way. Commented Apr 18, 2014 at 7:40
  • Both are undefined. Commented Apr 18, 2014 at 7:41
  • @deceze: that has no effect on that, they will both return undefined. Commented Apr 18, 2014 at 7:41
  • @OneKitten Exactly my point. Commented Apr 18, 2014 at 7:41

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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

0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.