每日3題
1 以下代碼執行后,控制臺中的輸出內容為?
// 以下代碼執行后,控制臺中輸出的內容是什么
var fullname = "a";
var obj = {
fullname: "b",
prop: {
fullname: "c",
getFullname: function () {
return this.fullname;
},
},
};
console.log(obj.prop.getFullname());
var test = obj.prop.getFullname;
console.log(test());
2 以下代碼執行后,控制臺中的輸出內容為?
// 以下代碼執行后,控制臺中輸出的內容是什么
function Foo() {
Foo.a = function () {
console.log(1);
};
this.a = function () {
console.log(2);
};
}
Foo.prototype.a = function () {
console.log(3);
};
Foo.a = function () {
console.log(4);
};
Foo.a();
let obj = new Foo();
obj.a();
Foo.a();
3 以下代碼執行后,控制臺中的輸出內容為?
// 以下代碼執行后,控制臺中輸出的內容是什么
function getName() {
for (let i = 0; i < 5; i++) {
setTimeout((_) => {
console.log(i);
}, i * 1000);
}
return
{
name: "aaa";
}
}
console.log(getName());
- 公眾號【今天也要寫bug】更多前端面試題
答案及決議
1
// 答案:c a
// 考察 this 系結規則
var fullname = "a";
var obj = {
fullname: "b",
prop: {
fullname: "c",
getFullname: function () {
return this.fullname; // 普通函式中的 this 在其運行時才能確定
},
},
};
console.log(obj.prop.getFullname()); // 隱式系結:呼叫位置有背景關系物件:prop,this指向它,因此輸出 c
var test = obj.prop.getFullname;
console.log(test()); // 默認系結:獨立函式呼叫,this 指向全域物件,即 window
// 而在瀏覽器中,var 宣告的全域變數會成為全域物件的屬性
// 所以 test() 執行后回傳 window.fullname=a
2
// 答案:4 2 1
// 考察:原型鏈、new 創建物件的程序、函式本身也是物件
function Foo() {
Foo.a = function () {
console.log(1);
};
this.a = function () {
console.log(2);
};
// new 創建物件時讓新創建的物件作為 this 的背景關系
// 所以這里的 this 指向下面創建的 obj
// 即在 obj 上添加了屬性 a
}
Foo.prototype.a = function () {
console.log(3);
};
// 在物件 Foo 上添加屬性 a:指向一個普通函式
Foo.a = function () {
console.log(4);
};
Foo.a(); // 呼叫上面那個普通函式,輸出 4
let obj = new Foo();
obj.a(); // 在建構式中添加了屬性 a,呼叫后輸出 2
Foo.a(); // 在創建 obj 時已經改變了物件 Foo 上的屬性 a 的指向,輸出 1
3
// 答案:undefined 0 1 2 3 4
// 考察事件回圈、return 陳述句
function getName() {
for (let i = 0; i < 5; i++) {
setTimeout((_) => {
console.log(i);
}, i * 1000);
}
// return 關鍵字和被回傳的運算式之間不允許使用行終止符
// 即 return 后要回傳的運算式不能換行,否則回傳 undefined
return
{
name: "aaa";
}
}
console.log(getName()); // 1
// setTimeout 是宏任務,在這里會在陳述句 1 執行之后執行
// getName 函式回傳 undefined,因此先輸出 undefined
// 之后 setTimeout 依次執行,分別輸出 0 1 2 3 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/508829.html
標籤:JavaScript
上一篇:自適應布局和回應式布局的區別?
