call和apply的理解

来源:互联网 发布:易语言数据库怎么用 编辑:程序博客网 时间:2024/06/11 15:25


一、方法的继承

function Animal() {
this.name = "Animal";
this.showName = function () {
alert(this.name);
}
}
function Cat() {
this.name = "Cat";
}
var animal = new Animal();
var cat = new Cat();
//通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。
//输入结果为"Cat"
animal.showName.call(cat, ",");
//animal.showName.apply(cat,[]);

注: call 的意思是把 animal 的方法放到cat上执行,原来cat是没有showName() 方法,现在是把animal 的showName()方法放到 cat上来执行,所以this.name 应该是 Cat

二、对象(类)的继承

function Animal(name) {

this.name = name;
this.showName = function () {
alert(this.name);
}
}
function Cat(name) {
Animal.call(this, name);
}
var cat = new Cat("Black Cat");

cat.showName();

注: Animal.call(this) 的意思就是使用 Animal对象代替this对象,那么 Cat中不就有Animal的所有属性和方法了吗,Cat对象就能够直接调用Animal的方法以及属性了.

三、多重继承

function Class10() {
this.showSub = function (a, b) {
alert(a - b);
}
}
function Class11() {
this.showAdd = function (a, b) {
alert(a + b);
}
}
function Class2() {
Class10.call(this);
Class11.call(this);
}

注: 很简单,使用两个 call 就实现多重继承了

0 0
原创粉丝点击