前端面試筆記 - js相關

請解釋事件代理 (event delegation)。

將單個事件綁定在父對象上,利用冒泡機制,監聽來自子元素的事件。javascript

優勢:解決子元素增長刪除時候的事件處理,防止內存泄漏css

事件捕獲:當某個元素觸發某個事件(如onclick),頂層對象document就會發出一個事件流,隨着DOM樹的節點向目標元素節點流去,直到到達事件真正發生的目標元素。在這個過程當中,事件相應的監聽函數是不會被觸發的。html

事件目標:當到達目標元素以後,執行目標元素該事件相應的處理函數。若是沒有綁定監聽函數,那就不執行。java

事件起泡:從目標元素開始,往頂層元素傳播。途中若是有節點綁定了相應的事件處理函數,這些函數都會被一次觸發。若是想阻止事件起泡,可使用e.stopPropagation()(Firefox)或者e.cancelBubble=true(IE)來組織事件的冒泡傳播。express

請解釋 JavaScript 中 this 是如何工做的。

stackoverflow數組

  • 在全局環境時
// this 表示window

function f(){
    return this //也是window
}
  • 放在object方法裏面時

this綁定到包含他的對象瀏覽器

var obj = {
    name: "obj",
    f: function () {
        return this + ":" + this.name;
    }
};
document.write(obj.f());
var obj = {
    name: "obj1",
    nestedobj: {
        name:"nestedobj",
        f: function () {
            return this + ":" + this.name;
        }
    }            
}

document.write(obj.nestedobj.f()); //[object Object]:nestedobj

即便你隱式的添加方法到對象,this仍然指向
當即父對象安全

var obj1 = {
    name: "obj1",
}

function returnName() {
    return this + ":" + this.name;
}

obj1.f = returnName; //add method to object
document.write(obj1.f()); //[object Object]:obj1
  • 當調用一個無上下問的函數

當函數調用沒有包含上下文,this將綁定到global對象閉包

var context = "global";

var obj = {  
    context: "object",
    method: function () {                  
        function f() {
            var context = "function";
            return this + ":" +this.context; 
        };
        return f(); //invoked without context
    }
};

document.write(obj.method()); //[object Window]:global
  • 當使用在構造函數時

即便用new關鍵字時,this指向剛建立的對象app

var myname = "global context";
function SimpleFun()
{
    this.myname = "simple function";
}

var obj1 = new SimpleFun(); //adds myname to obj1
//1. `new` causes `this` inside the SimpleFun() to point to the
//   object being constructed thus adding any member
//   created inside SimipleFun() using this.membername to the
//   object being constructed
//2. And by default `new` makes function to return newly 
//   constructed object if no explicit return value is specified

document.write(obj1.myname); //simple function
  • 當內部對象定義在原型鏈時

當一個方法定義在對象原型鏈,this指向調用該方法的對象

var ProtoObj = {
    fun: function () {
        return this.a;
    }
};
//Object.create() creates object with ProtoObj as its
//prototype and assigns it to obj3, thus making fun() 
//to be the method on its prototype chain

var obj3 = Object.create(ProtoObj);
obj3.a = 999;
document.write(obj3.fun()); //999

//Notice that fun() is defined on obj3's prototype but 
//`this.a` inside fun() retrieves obj3.a
  • 在 call(), apply() and bind() 函數內部
fun.apply(obj1 [, argsArray])
fun.call(obj1 [, arg1 [, arg2 [,arg3 [, ...]]]]) 
設置this函數並執行
fun.bind(obj1 [, arg1 [, arg2 [,arg3 [, ...]]]])
設置this
  • this在事件處理上

若是函數在eventHandler和onclick直接被調用 this指向元素(currentTarget)
不然執行window

<script> 
    function clickedMe() {
       alert(this + " : " + this.tagName + " : " + this.id);
    } 
    document.getElementById("button1").addEventListener("click", clickedMe, false);
    document.getElementById("button2").onclick = clickedMe;
    document.getElementById("button5").attachEvent('onclick', clickedMe);   
</script>

<h3>Using `this` "directly" inside event handler or event property</h3>
<button id="button1">click() "assigned" using addEventListner() </button><br />
<button id="button2">click() "assigned" using click() </button><br />
<button id="button3" onclick="alert(this+ ' : ' + this.tagName + ' : ' + this.id);">used `this` directly in click event property</button>

<h3>Using `this` "indirectly" inside event handler or event property</h3>
<button onclick="alert((function(){return this + ' : ' + this.tagName + ' : ' + this.id;})());">`this` used indirectly, inside function <br /> defined & called inside event property</button><br />

<button id="button4" onclick="clickedMe()">`this` used indirectly, inside function <br /> called inside event property</button> <br />

IE only: <button id="button5">click() "attached" using attachEvent() </button>

請解釋原型繼承 (prototypal inheritance) 的原理。

當定義一個函數對象的時候,會包含一個預約義的屬性,叫prototype,這就屬性稱之爲原型對象。

function F(){};
console.log(F.prototype)
//F.prototype包含
//contructor構造函數

JavaScript在建立對象的時候,都會有一個[[proto]]的內置屬性,用於指向建立它的函數對象的prototype。原型對象也有[[proto]]屬性。所以在不斷的指向中,造成了原型鏈。

//函數對象
function F(){};
F.prototype = {
    hello : function(){}
};
var f = new F();
console.log(f.__proto__)

當使用new去調用構造函數時,至關於執行了

var o = {};
o.__proto__ = F.prototype;
F.call(o);

原型對象prototype上都有個預約義的constructor屬性,用來引用它的函數對象。這是一種循環引用。

function F(){};
F.prototype.constructor === F;
( new Foo ).__proto__ === Foo.prototype
( new Foo ).prototype === undefined

__proto__真正的原型鏈
prototype只存在與構造函數中

你怎麼看 AMD vs. CommonJS?

請解釋爲何接下來這段代碼不是 IIFE (當即調用的函數表達式):function foo(){ }();.

沒有加括號

要作哪些改動使它變成 IIFE?

描述如下變量的區別:null,undefined 或 undeclared?

該如何檢測它們?

null===null
undefined === undefined

什麼是閉包 (closure),如何使用它,爲何要使用它?

函數閉包(function closures),是引用了自由變量的函數。這個被引用的自由變量將和這個函數一同存在,即便已經離開了創造它的環境也不例外

請舉出一個匿名函數的典型用例?

回調

你是如何組織本身的代碼?是使用模塊模式,仍是使用經典繼承的方法?

請指出 JavaScript 宿主對象 (host objects) 和原生對象 (native objects) 的區別?

請指出如下代碼的區別:function Person(){}、var person = Person()、var person = new Person()?

.call 和 .apply 的區別是什麼?

apply 第二個參數是數組
call 第二個之後的可變參數

請解釋 Function.prototype.bind?

在何時你會使用 document.write()?

寫script

請指出瀏覽器特性檢測,特性推斷和瀏覽器 UA 字符串嗅探的區別?

請儘量詳盡的解釋 Ajax 的工做原理。

XMLHttpRequest

使用 Ajax 都有哪些優劣?

請解釋 JSONP 的工做原理,以及它爲何不是真正的 Ajax。

經過在網頁中加入script標籤,是瀏覽器經過get方式加載一段js代碼

你使用過 JavaScript 模板系統嗎?

若有使用過,請談談你都使用過哪些庫?

請解釋變量聲明提高 (hoisting)。

經過 var 聲明的變量在代碼執行以前被js引擎提高到了當前做用域的頂部

請描述事件冒泡機制 (event bubbling)。

一個事件被觸發,會發生先捕獲後冒泡的行爲。
冒泡機制指一個事件從發生元素開始先父元素傳遞,直到達到根元素

"attribute" 和 "property" 的區別是什麼?

js dom 對象擁有的property,property有不少類型
attribute是指html擁有的特性,類型是字符串

爲何擴展 JavaScript 內置對象不是好的作法?

請指出 document load 和 document DOMContentLoaded 兩個事件的區別。

DomContentLoaded事件發生在domcument對象被初始化完成,css,圖片和frame還沒被加載的時候

load事件表示資源被所有加載

== 和 === 有什麼不一樣?

==會發生類型轉換
===不會發生類型轉換

請解釋 JavaScript 的同源策略 (same-origin policy)。

同源策略限制從一個源加載的文檔或腳本如何與來自另外一個源的資源進行交互

http://store.company.com/dir2... 成功
http://store.company.com/dir/... 成功
https://store.company.com/sec... 失敗 不一樣協議 ( https和http )
http://store.company.com:81/dir/etc.html 失敗 不一樣端口 ( 81和80)
http://news.company.com/dir/o... 失敗 不一樣域名 ( news和store

如何實現下列代碼:

[1,2,3,4,5].duplicator(); // [1,2,3,4,5,1,2,3,4,5]
Arrry.prototype.duplicator = function(){
    return this.concat(this)
}

什麼是三元表達式 (Ternary expression)?「三元 (Ternary)」 表示什麼意思?

什麼是 "use strict"; ? 使用它的好處和壞處分別是什麼?

"use strict" 告訴js運行時以嚴格模式執行javascript語句
使js以更安全的方式執行,對某些行爲直接報錯

請實現一個遍歷至 100 的 for loop 循環,在能被 3 整除時輸出 "fizz",在能被 5 整除時輸出 "buzz",在能同時被 3 和 5 整除時輸出 "fizzbuzz"。

for(let i=1;i<=100;i++){
    let word = ""
    if(i % 3 ==0){
        word += "fizz"
    }
    if(i % 5 ==0){
        word += "buzz"
    }
    if(word){
        console.log(word)
    }
}

爲什麼一般會認爲保留網站現有的全局做用域 (global scope) 不去改變它,是較好的選擇?

爲什麼你會使用 load 之類的事件 (event)?此事件有缺點嗎?你是否知道其餘替代品,以及爲什麼使用它們?

請解釋什麼是單頁應用 (single page app), 以及如何使其對搜索引擎友好 (SEO-friendly)。

單頁應用是指全部的資源交互都放在一個頁面,而不是交互的時候跳轉到另外一個頁面。
使用ssr服務端渲染。

你使用過 Promises 及其 polyfills 嗎? 請寫出 Promise 的基本用法(ES6)。

new Promise(resolve,reject)
Promise.resolve
Promise.reject

使用 Promises 而非回調 (callbacks) 優缺點是什麼?

將回調轉換成鏈式調用

使用一種能夠編譯成 JavaScript 的語言來寫 JavaScript 代碼有哪些優缺點?

你使用哪些工具和技術來調試 JavaScript 代碼?

console.log
debuger

你會使用怎樣的語言結構來遍歷對象屬性 (object properties) 和數組內容?

array array.foreach
object for var i in xx i是字符串

請解釋可變 (mutable) 和不變 (immutable) 對象的區別。

mutable
imuutable表示對象建立後就再也不變化

請舉出 JavaScript 中一個不變性對象 (immutable object) 的例子?

不變性 (immutability) 有哪些優缺點?

能夠比較對象,線程安全
缺點就是費內存

如何用你本身的代碼來實現不變性 (immutability)?

請解釋同步 (synchronous) 和異步 (asynchronous) 函數的區別。

同步是指順序執行,會有阻塞
異步是指函數當即執行並返回

什麼是事件循環 (event loop)?

主線程運行的時候,產生堆(heap)和棧(stack),棧中的代碼調用各類外部API,它們在"任務隊列"中加入各類事件(click,load,done)。只要棧中的代碼執行完畢,主線程就會去讀取"任務隊列",依次執行那些事件所對應的回調函數。

請問調用棧 (call stack) 和任務隊列 (task queue) 的區別是什麼?

javascript中的全部任務分爲兩類,
一類是同步任務,另外一種是一部任務。
全部的同步任務都在主線程上執行,
當同步任務執行完在執行異步任務。

call stack 指主線線程執行任務的地方,當調用棧爲空的時候,
會去輪詢task queue,而後將隊列裏的任務加入棧中執行
tast queue 按照包含一系列任務的隊列

解釋 function foo() {} 與 var foo = function() {} 用法的區別

第一個表示生成一個命名的函數
第二個表示生成一個匿名函數 ,並賦值給foo

What are the differences between variables created using let, var or const?

let var const都表示申明一個變量

var的做用因而函數體的所有,會發生做用於提高
let,const是塊級做用域
let表示能夠被屢次賦值
const表示只能被一次賦值

{} + {}

js的加法只有兩種

  1. 字符串和字符串的相加
  2. 數字和數字的相加

加法運算會觸發三種轉換

  1. 原始值
  2. 數字
  3. 字符串
> [] + []
''
//[].toString()爲空字符串,空字符串相加

> [] + {}
'[object Object]'

> {} + {}
'NaN' 
// 火狐下爲NaN 由於第一個對象看成空代碼塊,實際執行爲 +{}
相關文章
相關標籤/搜索