更新時間:2022-12-14 15:59:28 來源:動力節點 瀏覽1126次
問題1:JavaScript 中 undefined 和 not defined 的區別
JavaScript 未聲明變量直接使用會拋出異常:var name is not defined,如果沒有處理異常,代碼就停止運行了。但是,使用typeof undeclared_variable并不會產生異常,會直接返回 undefined。
var x; // 聲明 x
console.log(x); //output: undefined
console.log(typeof y); //output: undefined
console.log(z); // 拋出異常: ReferenceError: z is not defined
問題2:下面的代碼輸出什么?
var y = 1;
if (function f(){}) {
y += typeof f;
}
console.log(y);
正確的答案應該是 1undefined。
JavaScript中if語句求值其實使用eval函數,eval(function f(){}) 返回 function f(){} 也就是 true。
下面我們可以把代碼改造下,變成其等效代碼。
var k = 1;
if (1) {
eval(function foo(){});
k += typeof foo;
}
console.log(k);
上面的代碼輸出其實就是 1undefined。為什么那?我們查看下 eval() 說明文檔即可獲得答案
該方法只接受原始字符串作為參數,如果 string 參數不是原始字符串,那么該方法將不作任何改變地返回。
恰恰 function f(){} 語句的返回值是 undefined,所以一切都說通了。
注意上面代碼和以下代碼不同。
var k = 1;
if (1) {
function foo(){};
k += typeof foo;
}
console.log(k); // output 1function
問題3:在JavaScript中創建一個真正的private方法有什么缺點?
每一個對象都會創建一個private方法的方法,這樣很耗費內存
觀察下面代碼
var Employee = function (name, company, salary) {
this.name = name || "";
this.company = company || "";
this.salary = salary || 5000;
// Private method
var increaseSalary = function () {
this.salary = this.salary + 1000;
};
// Public method
this.dispalyIncreasedSalary = function() {
increaseSlary();
console.log(this.salary);
};
};
// Create Employee class object
var emp1 = new Employee("John","Pluto",3000);
// Create Employee class object
var emp2 = new Employee("Merry","Pluto",2000);
// Create Employee class object
var emp3 = new Employee("Ren","Pluto",2500);
在這里 emp1,emp2,emp3都有一個increaseSalary私有方法的副本。
所以我們除非必要,非常不推薦使用私有方法。
問題4:JavaScript中什么是閉包?寫出一個例子
老生常談的問題了,閉包是在一個函數里聲明了另外一個函數,并且這個函數訪問了父函數作用域里的變量。
下面給出一個閉包例子,它訪問了三個域的變量
var globalVar = "abc";
// Parent self invoking function
(function outerFunction (outerArg) { // begin of scope outerFunction
// Variable declared in outerFunction function scope
var outerFuncVar = 'x';
// Closure self-invoking function
(function innerFunction (innerArg) { // begin of scope innerFunction
// variable declared in innerFunction function scope
var innerFuncVar = "y";
console.log(
"outerArg = " + outerArg + "\n" +
"outerFuncVar = " + outerFuncVar + "\n" +
"innerArg = " + innerArg + "\n" +
"innerFuncVar = " + innerFuncVar + "\n" +
"globalVar = " + globalVar);
}// end of scope innerFunction)(5); // Pass 5 as parameter
}// end of scope outerFunction )(7); // Pass 7 as parameter
innerFunction is closure that is defined inside outerFunc
輸出很簡單:
outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc
以上就是“四個Javascript必問面試題,你看看全會嗎”,你能回答上來嗎?如果想要了解更多的Java面試題相關內容,可以關注動力節點Java官網。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習