JS Typical Questions

原创转载请注明出处: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 被关键字var声明,说明 a 是这个函数的局部变量,所以函数外打印 a, 会显示错误 not defined,

b 没有被关键字var声明,JS默认 b 是一个全局作用域,所以函数外打印 b,会显示 5

 

另外如果使用 'use strict'; 会直接报错

(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/

你可能感兴趣的:(JavaScript,javascript)