JS映射

this,[function].caller

arguments,arguments.callee

apply,call

constructor,prototype

我把以上这些个对象(方法?成员?) 归入JS运行时的映射 可能不是很贴切 希望这样能便于理解

this , [function].caller:当前运行域映射
this 代表调用当前运行代码的对象,当没有显示调用时,代表由window(最外层全局根对象)调用,this在运行时是必定存在的
 

//以下方法可以感觉this的变化

function run(){

window.name='kk'

function a(){}

function b(){alert(this.name)}

a.prototype.b=b;

a.prototype.name='kka'

new a().b();

b();

}

run()

[function].caller 被调用代码外层function引用,可能会是null
 

function a(){alert(a.caller);}

function b(){a();}

a();

b();

arguments,arguments.callee
 arguments  在function运行时可以获取,代表当前function运行中传入的参数集合(注意它类似Array但并不是Array对象)
 

function sum(){

alert("传入的参数数量:"+arguments.length);

var arg='';

var v=0;

for(var i=0;i<arguments.length;i++){arg+=arguments[i]+',';

v+=arguments[i];}

alert('传入参数值:'+arg);

alert('合计:'+v);

}
sum(1,3,5,7)

arguments.callee 获取当前运行function本身,这样可以在匿名函数中引用到本体运行的function
 

(function(n){

if(window.confirm('第'+n+'次调用,要继续吗?')){

arguments.callee(n+1)

}

}

)(1)

apply,call
apply,call 指定function运行的域,有就是指定this,他们的区别就在于传入参数不同方式

function.apply(object,[arg1,arg2...])

function.call(object,arg1,arg2...)

 

 

var o1={sum:function(x,y){alert("o1.sum:"+x+y);}}

var o2={sum:function(x,y){alert("o2.sum:"+(x+y));}}
var run=function(x,y){this.sum(x,y);}
run.apply(o1,[1,2]);
run.apply(o2,[1,2]);
run.call(o1,1,2);
run.call(o2,1,2);

//apply可以方便的传递参数集合

//接上面

function applyrun(){

run.apply(o1,arguments);

run.apply(o2,arguments);

}

applyrun(1,2)

 

function applyrun(){

run.apply(o1,arguments);

run.apply(o2,arguments);

}

applyrun(1,2)
object.constructor,function.prototype
 constructor  生成指定对象的function引用
 

function f(){var a=1}
alert(new f().constructor)
alert(f.constructor)  //体会下和上面的区别

 

alert(new Object().constructor)
alert({}.constructor)

 

alert(new Number(2).constructor)
alert((1).constructor)

alert(new String('1').constructor)
alert('1'.constructor)

 

function.prototype

原型属性 这也是JS语言的一大特性

简单说明如下:

a is function   // a 是一个 function

A == new a()  //A是a的实例

则 A能直接调用a.prototype的成员(注意是直接)

 

 

//prototype是一个复杂的概念 下面是一个简单的使用

function base(name){this.name=name?name:'base';}

base.prototype.show=function(){alert(this.name);}

var a1=new base('a1');

var a2=new base('a2');

a1.show();

a2.show();

//为什么要有prototype这个概念 基本来说是为了成员的重用 和实例的扩展

/*prototype的成员并没有在每个成员中拥有一个副本 也就是某个function的不同实例针对prototype成员的调用 是同一个成员。 某个function的ptototype的更改将影响所该function的所有实例

*/

//接上面

base.prototype.setname=function(name){this.name=name;}

a1.setname('a1 new name');

a2.setname('a2 new name');

a1.show();

a2.show();

instanceof typeof
typeof

 

typeof 对象

instanceof  

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值