2014年9月23日 星期二

Javascript 重要的五的考題.

來源: http://www.sitepoint.com/5-typical-javascript-interview-exercises/

1.Scope
(function() { var a = b = 5; })(); console.log(b);

Ans: 5 , 因為 b 沒用 var , 等同於 var a = window.b = 5 ; (function() { 'use strict'; var a = window.b = 5; })(); console.log(b); 

2: Create “native” methods 
console.log('hello'.repeatify(3));

Ans: String.prototype.repeatify = String.prototype.repeatify || function(times) { var str = ''; for (var i = 0; i < times; i++) { str += this; } return str; };

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

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

4: How this work 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());

Ans: Aurelio De Rosa and John Doe.
因為第二種方式, this 被指到 window 了.

5: Use call() and apply()

Ans: console.log(test.call(obj.prop));

【下列文章您可能也有興趣】

沒有留言: