美文网首页
call和apply的区别 函数的继承 新增选择器

call和apply的区别 函数的继承 新增选择器

作者: 冷暖自知_2237 | 来源:发表于2019-04-09 20:56 被阅读0次

call和apply的区别

二者都可以改变当前的this,区别在于apply方法要将参数放入数组中再传参

function aa(a,b){

alert('我的this是' + this + ',我的a是' + a + ',我的b是' + b);

}

//我的this是[object Window],我的a是2,我的b是3

// aa(2,3);

//我的this是abc,我的a是2,我的b是3

// aa.call('abc',2,3);

//我的this是abc,我的a是2,我的b是3

aa.apply('abc', [2,3]);

函数的继承

function Fclass(name, age){

this.name = name;

this.age = age;

}

Fclass.prototype.showName = function(){

alert(this.name);

}

Fclass.prototype.showAge = function(){

alert(this.age);

}

//子类

function Sclass(name, age, job){

//属性用call或者apply的方式来继承

Fclass.call(this, name, age);

this.job = job;

}

//方法继承:将父类的一个实例赋值给子类的原型属性

Sclass.prototype = new Fclass();

Sclass.prototype.showJob = function(){

alert(this.job);

}

//由于已经继承了父类的属性和方法,所以可以直接调用

var Driver = new Sclass('tom',18,'老司机');

Driver.showName();

Driver.showAge();

Driver.showJob();

新增选择器

window.onload = function(){

var oDiv = document.querySelector('#div1');

alert(oDiv);//弹出[object HTMLDivElement],表示选择了该Div

//如果要选择多个元素用querySelectorAll

var aLi = document.querySelectorAll('.list li');

alert(aLi.length);//8

}

相关文章

网友评论

      本文标题:call和apply的区别 函数的继承 新增选择器

      本文链接:https://www.haomeiwen.com/subject/ikhwiqtx.html