开心

javascript call apply

call :

call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 
  如果没有提供 thisObj 参数,那么 Global 对象被用作thisObj。说明白一点其实就是更改对象的内部指针,即改变对象的this指向的内容。这在面向对象的js编程过程中有时是很有用的。

apply:

应用某一对象的一个方法,用另一个对象替换当前对象。 

如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

 

 

function Animal(xx){

this.name='zhu'
this.showName=function (cc,jj){
alert(this.name+cc+','+jj);


}
alert(this.name+xx);
}
function Cat()
{
this.name='cat';

}
//var animal=new Animal();
//var cat=new Cat();
Animal.call(Cat,'df');
//this.name;

Animal.apply();
//this.name;

 

 

var zhu=function(name){this.name=name};
var ben=function(sex){this.sex=sex;}
var xi=function(age){this.age=age;}
var people=function(name,sex,age,score){zhu.call(this,name);ben.call(this,sex);xi.call(this,age);this.score=score;}
people.prototype.construction=people;
var p=new people('zhao','male','11','78');
console.log(p.name);
console.log(p.sex);
console.log(p.age);
console.log(p.score);

 

 

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

 

 

function Animal(){

this.name='Animal';
this.showName=function(aa){
alert(this.name+aa);
}
}
function Cat()
{
this.name='Cat';
}
var animal=new Animal();
var cat=new Cat();
animal.showName.call(cat,'kk');

 

 

function add(a,b)
{
alert(a+b);
}
function sub(a,b)
{
alert(a-b);
}
add.call(sub,4,9);

 

 

function base(){this.member="a people";this.method=function(){window.alert(this.member);}}
function extend()
{
base.call(this);

window.alert(member);
method();
window.alert(this.method);
}
extend();

 

var ClassA={create:function(){ return function(){ this.cc.apply(this,arguments);this.ee.apply(this,arguments); } }} var vehicle=ClassA.create(); vehicle.prototype={ee:function(uu,kk){alert("0")} ,cc:function(type,xx){this.type=type;this.xx=xx;},showSelf:function(){ alert(this.xx+"this +vehile"+this.type);}} var moto=new vehicle("Moto","lll"); moto.showSelf();

 

var a="jjj"; var b="abc";var func=new function(){this.a="func";this.b="bbb";} var myfunc=function(x){ var a="myfunc";this.b="kkk"; alert(this.a); alert(this.b); }; myfunc.call(func,"var");

posted @ 2016-05-30 18:34  大喜  阅读(176)  评论(0编辑  收藏  举报
坦然 会增进信任 - 信任 感情才会升华