JS Typical Questions

Please indicate the source of the original reprint: http://agilestyle.iteye.com/blog/2370610

 

Scope

(function() {
   var a = b = 5;
})();

console.log(a);
console.log(b);
ReferenceError: a is not defined
5

Note:

a is declared by the keyword var, indicating that a is a local variable of this function, so printing a outside the function will display the error not defined,

b is not declared with the keyword var, JS default b is a global scope, so printing b outside the function will display 5

 

In addition, if 'use strict'; is used, an error will be reported directly

(function() {
   'use strict';
   var a = b = 5;
})();

console.log(a);
console.log(b);
ReferenceError: b is not defined

 

Create “native” methods

Define a repeatify function on the String object. The function accepts an integer that specifies how many times the string has to be repeated. The function returns the string repeated the number of times specified. For example: 

console.log('hello'.repeatify(3));

Should print hellohellohello

String.prototype.repeatify = String.prototype.repeatify || function(times) {
   var str = '';

   for (var i = 0; i < times; i++) {
      str += this;
   }

   return str;
};

console.log('hello'.repeatify(3));

 

Hoisting

function test() {
   console.log(a);
   console.log(foo());
   
   var a = 1;
   function foo() {
      return 2;
   }
}

test();
undefined
2

Note:

The reason is that both variables and functions are hoisted (moved at the top of the function) but variables don’t retain any assigned value. So, at the time the variable a is printed, it exists in the function (it’s declared) but it’s still undefined. 

  

How this works in JavaScript

var fullname = 'John Doe';
var obj = {
   fullname: 'Colin Ihrig',
   prop: {
      fullname: 'Aurelio De Rosa',
      getFullname: function() {
         return this.fullname;
      }
   }
};

console.log(obj.prop.getFullname());

var test = obj.prop.getFullname;

console.log(test());
Aurelio De Rosa
John Doe

Note:

The reason is that the context of a function, what is referred with the this keyword, in JavaScript depends on how a function is invoked, not how it’s defined.

In the first console.log() call, getFullname() is invoked as a function of the obj.prop object. So, the context refers to the latter and the function returns the fullname property of this object. On the contrary, when getFullname() is assigned to the test variable, the context refers to the global object (window). This happens because test is implicitly set as a property of the global object. For this reason, the function returns the value of a property called fullname of window, which in this case is the one the code set in the first line of the snippet. 

 

 

Reference

https://www.sitepoint.com/5-typical-javascript-interview-exercises/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326814573&siteId=291194637