JavaScriptのCallとAppleyの違いを整理します.
3336 ワード
function classA() {
this.name='bluedestiny';
this.show = function () {
// alert(this.name);
}
}
function classB() {
this.name = 'never-online';
}
var objA = new classA();
var objB = new classB();
//call
// objA show objB
objA.show.call(objB);
function methods(a,b) {
return arguments[0] + arguments[1] + a + b;
}
//applyy , (methods )
var Result = methods.apply(this,["BBBB","CCC"]);
alert(Result);
//call , (methods )
Result = methods.call(this,"BBBB","CCC");
alert(Result);
var Class = {
create: function() {
// new (), function
return function() {
this.initialize.apply(this, arguments);
}
}
};
var vehicle=Class.create();
vehicle.prototype={
initialize:function(type){
this.type=type;
},
showSelf:function(){
alert("this vehicle is "+ this.type);
}
}
// new
var moto=new vehicle("Moto");
// moto initialize , , vehicle initialize , , , initialize apply , new A(‘helloWord!') initialize apply 。 。
moto.showSelf();
//this.initialize.apply(this , arguments);
// this, new , a, this 。 this( a) initialize , arguments ( ), , a initialize , “initialize” 。
// apply(javascript prototype ):
Function.prototype.bind = function() {
var __method = this;
var args = $A(arguments);
var object = args.shift();
return function() {
// apply , object , args bind ( )
return __method.apply(object, args.concat($A(arguments)));// , $A(arguments)
}
}
// :
// bind ,
//a) var __method = this; Function Context , Closure( javascript , " ") , 。 bind , 。
//b) var args = $A(arguments); arguments , $A(arguments) bind array.
//c) var object = args.shift(); args Target Object( ), args (array)
//d) , ( ), apply __method(bind ) Target Object( ), Target Object( ) args.concat($A(arguments)), Target Object( ) __method 。
// , Function Context 。
var ClassName = function(v){
this.value=v;
this.getValue=function(){
return this.value;
}
this.setValue=function(v){
this.value=v;
}
}
var objectName1 = new ClassName(“a”);//
// objectName1 ClassName , ClassName this new , objectName1 。 :
// :
objectName1.setValue(''hello'');
alert(objectName1.getValue());// hello
alert(objectName1.value) ;// hello
var objectName2 = ClassName(“b”);//
// objectName2 ? , ClassName ( )。 ClassName , objectName2 undifinded “b” ? , , “b” window, :
var objectName2 = ClassName(“b”);//
alert(window.value);// b