JavaScript Quiz #12

Assume that we have the following short JavaScript code:

<script>
    var number = 50;
    var obj = {
        number: 60,
        getNum: function () {
	    var number = 70;
	    return this.number;
	}
    }; 

    alert(obj.getNum());
    alert(obj.getNum.call());
    alert(obj.getNum.call({number:20}));
</script> 

Will this code succeed or fail? and if it succeeds, what is the output of the alerts?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The code will work fine. The alerts will output 60, 50 and 20. Let’s understand why we will have these results.

The sequence of operations:
1. In obj.getNum(), this.number will return number in obj scope which is 60.
2. In obj.getNum.call(), this.number will return number in global scope because Function.prototype.call‘s first parameter is not
specified which mean that the scope will be the global scope. So the result will be 50.
3. In obj.getNum.call({number:20}), this.number will return number in the object scope specified in the first parameter
of Function.prototype.call method which is {number: 20}. So the result will be 20.

More information about Function.prototype.call() can be found here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

One thought on “JavaScript Quiz #12

  1. Pingback: JavaScript Quiz #12 | Technical Advices, "An advice can always help"

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


Warning: fsockopen() [function.fsockopen]: php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/content/83/10439583/html/wp-content/plugins/sweetcaptcha-revolutionary-free-captcha-service/library/sweetcaptcha.php on line 71

Warning: fsockopen() [function.fsockopen]: unable to connect to www.sweetcaptcha.com:80 (php_network_getaddresses: getaddrinfo failed: Name or service not known) in /home/content/83/10439583/html/wp-content/plugins/sweetcaptcha-revolutionary-free-captcha-service/library/sweetcaptcha.php on line 71
Couldn't connect to server: php_network_getaddresses: getaddrinfo failed: Name or service not known (0)