0

I have a(most likely simple and bumd) question about objects. I created the object "jon" of the instance "Person". When I call

console.log(jon.name)

the console will give me out "jon". So far so good.

After running the code and typing in the console itself

jon.name

I was expecting to get "jon" as a result, but the console showed me that jon is undefined. Could someone explain me why?

Here´s a code snippet: https://jsfiddle.net/Fasyx/w0q1rqh0/

0

1 Answer 1

1

The code in jsfiddle runs in scope of another function or some kind of a send-box that's why variable jon is not available in global scope.

If you create simple html file with <script> tag with you code inside and open it in browser you will get the behavior you expect:

<script>
    var Person = function(name, age) {
        this.name = name;
        this.age = age;
    }

    var jon = new Person("jon", 24);
    console.log(jon.name + " " + jon.age)
</script>

If you access jon in console you will find the object because it is part of global scope now.

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

1 Comment

Ah, just set up a server and run .html with the script in there. Perfect - thank you Andrii!

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.