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); } | |
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));}} //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 Object().constructor) alert({}.constructor)
alert(new Number(2).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 |