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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值