1. 關(guān)于new
function fn(){
console.log(this)
}
new fn() //會執(zhí)行fn
答:this就是fn,它有fn.__proto__屬性。
fn.__proto__指向fn.prototype,fn的原型(fn.prototype)里有兩個屬性{constructor: fn()}和__proto__(指向Object.prototype)
- new會幫你創(chuàng)建臨時對象,并幫你return,可以用this訪問到
- 給你一個隱藏屬性
__proto__,幫你綁定類的原型fn.prototype - 并給原型兩個屬性
constructor: fn和__proto__(指向Object.prototype)
2. 用函數(shù)模擬一個類(new)
function Animal(species) {
this.species = species; //自有屬性
}
Animal.prototype = {
constructor: Animal,
walk : function () {}, //走路的代碼
run: function () {}, //跑步的代碼
eat: function () {}, //吃東西的代碼
sleep: function () {} //睡覺的代碼
};
let cat = new Animal('cat')
cat.specise === cat //true
//并且cat對象的__proto__指向Animal.prototype,有里面的動作屬性
- new會幫你創(chuàng)建臨時對象,并幫你return,可以用this訪問到
- 給你一個隱藏屬性
__proto__,幫你綁定類的原型fn.prototype - 并給原型兩個屬性
constructor: Animal()和__proto__(指向Object.prototype)
3. MVC
-
MVC是Model View Controller
View:是這個js模塊對應(yīng)在html中的部分,就是展示給用戶看的那一部分Model:可以從服務(wù)器獲得數(shù)據(jù),把數(shù)據(jù)傳給Controller。還要將Controller監(jiān)聽到的用戶提交的數(shù)據(jù)上傳到服務(wù)器。
Controller:調(diào)用model的數(shù)據(jù),用來更新view。還要監(jiān)聽用戶在view上的操作,獲取用戶提交的數(shù)據(jù),傳給model。
代碼
window.Model = function(options){
let resourceName = options.resourceName;
return {
init : function(){},
fetch: function(){},
save: function(){}
}
}
window.View = function(selector){
return document.querySelector(selector);
}
window.Controller = function(options){
let init = options.init;
let object = {
view: null,
model: null,
init: function(view,model){
this.view = view;
this.model = model;
this.model.init();
init.call(this.view);
this.bindEvents.call(this)
}
};
for(let key in options){
if(key !== 'init'){
object[key] = options[key]
}
}
return object;
}
4. promise
promiseTest = function (a,b){
return new Promise(function(resolve,reject){
if(a+b>5){
resolve(); //若參數(shù)a+b大于五則執(zhí)行resolve
}else{
reject(); //若參數(shù)a+b大小于等于五則執(zhí)行resolve
}
})
}
使用:
promiseTest(4,6).then(
() => {
console.log('大于5');
},
() => {
console.log('小于5')
},
) //'大于5'