您的位置:首页 > 移动开发

关于js中call/apply的一点认识

2016-06-05 16:27 423 查看

上代码

function  Parent(a,b)
{
console.log(this.a,this.b);
// 如果单独调用joke()方法,会出现TypeError: this.joke is not a function,因为在Parent中并没有关于对joke()的定义,
//this.joke();

//  this.a =a;
//  this.b =b;
this.showname=function(a,b){
console.log('this a parent',a+b,a,b);
}

}

function Child(a,b)
{
this.a = a;
this.b = b;
this.joke = function()
{
console.log('I will tell you a joke ,Father');
}
//  从此以后,Child具备召唤父亲的能力,而父亲也具备使用儿子的能力??为什么呢?
//  本质:替换了函数的上下文,通俗点,在Parent的函数作用域内,this对象已经指代为Child 对象,
//  由此,Parent中的this其实也是Child的代表
//  但是单独使用Parent时,Parent并不具备Child的能力,因为也不清楚其有没有Child,对未来也不知,自然this一片空白
// 见证奇迹的时刻,父子合体==>>
Parent.call(this,a,b);
}
// 实际使用中:
var child = new Child(1,2);
child.showname(3,4);
console.log(child.a,child.b);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: