1.call,apply,bind —>更改this指向
* call方法和apply方法,第一個參數是this所要指向的那個對象,如果設爲null或undefined或者this,則等同於指定全局對象。
* 第二個參數有所不同
fun.call(thisArg, arg1, arg2, …)
fun.apply(thisArg, [argsArray])
貓吃魚,狗吃肉,奧特曼打小怪獸。
有天狗想吃魚了
貓.吃魚.call(狗,魚)
狗就吃到魚了
貓成精了,想打怪獸
奧特曼.打小怪獸.call(貓,小怪獸)
var cat={
add(a,b){
return a+b
},
eatFish(){
console.log('eat fish')
}
}
var dog={}
cat.add.apply(dog,[3,4]) //7
cat.add.call(dog,3,4) //7
cat.eatFish.call(dog) //'eat fish'
cat.eatFish.apply(dog) //'eat fish'
cat.add.bind(dog) //返回add函數,函數沒有執行
cat.add.bind(dog)(4,6) //返回add函數的執行結果 => 10
Math.min.call(null,1,4,2,4,8,0) //0
Math.min.apply(null,[1,4,2,4,8,0]) //0
2.Cookie,sessionStorage,localStorage的有什麼區別
* sessionStorage,loacalStorage 是HTML5提供的兩種存儲在客戶端的新方法。
* cookie在瀏覽器和服務器間來回傳遞,數據不能超過4k
sessionStorage:僅在當前瀏覽器窗口關閉前有效,自然也就不可能持久保持;
localStorage:始終有效,窗口或瀏覽器關閉也一直保存,因此用作持久數據;
3.去除兩個字符串中相同的字符
var a_str='abcdefgsadfasdfasd';
var b_str='dfsfauyiuykyy';
var a_Set=new Set(a_str); //set去重
var b_Set=new Set(b_str); //set去重
var [a_newStr,b_newStr]=['',''];
for(let item of a_Set.values()){
a_newStr+=item; //重新拼接字符串
}
for(let item of b_Set.values()){
b_newStr+=item; //重新拼接字符串
}
for(let i=0,l=a_newStr.length;i<=l;i++){
for(let j=0,len=b_newStr.length;j<=len;j++){
if(a_newStr[i]===b_newStr[j]){ //相同字符刪除
a_newStr=a_newStr.replace(a_newStr[i],'');
b_newStr=b_newStr.replace(b_newStr[j],'');
}
}
}
4.class繼承
class Parent{
constructor(x, y) {
this.x = x;
this.y = y;
}
print(){
console.log(`${this.x}---${this.y}`);
}
}
class Child extends Parent{ //繼承父
constructor(x,y,z){//子的構造器
super(x,y);
this.z='zi';
}
child(){
console.log(this.x+'----'+this.y+'----zi')
}
}
new Child(3,5,'zi').print();//調用父方法
new Child(3,5,'zi').child();//調用子方法
5.原型繼承和構造繼承
function fu(name){
this.name=name||'父';
}
fu.prototype.print=function(){
console.log('----'+this.name);
}
function zi(){};
zi.prototype=new fu();
zi.prototype.name='子';
new zi().print();
-----
function zi(name){
fu.call(this);
this.name=name||'子';
}
new zi('zi').print();
6.下面結果是什麼?
var [a,b,c]=[[1,2],[3,4],5];
function test(a,b,c){
a=[];
b[0]=6;
c=7;
console.log(a,b,c);
}
test(a,b,c);// [] [6,4] 7 傳址 傳值 b變量中數組的第二個元素的值未改變
var a; //聲明未賦值
a===window.a; //true 順序執行
if('a' in window){
a='hello';
console.log('先執行:'+a)
}
console.log('後執行:'+a)
先執行:hello //變量提升,js是同步執行代碼。
後執行:hello