Javascript函数深入研究:函数中判断自己是以哪种形式被调用的,是A(),还是new A()或者其它?

假设有一个函数A是这样的:

function A(){  }

可能的调用方式有:

new A();

A();

A.a=A; A.a();

A.prototype.b=A; b=new A(); b.b();

A.prototype.c=A; A.prototype.c();

d=new A(); d.d=A; d.d();

A.apply(new A());

A.call(new A());

A.apply(A);

A.call(A);

等。

本文通过一个比较全面的示例,展示如何在函数定义中对各种情形进行判断。

需要指出的是,有些情况是等效的,运行时无法进行区分。

主要用到的特性有:callee, constructor, hasOwnProperty, instanceof, prototype

 

直接查看在线演示,请狠狠点击这里

 

演示截图:

function-how-I-was-called

 

先看看我的示例文档的输出结果:

function Person(n,a){
    //......
}

 

Person();
1.上面是普通函数调用



Person.prototype.aa = Person;
var p = new Person();
2.上面是new Person() 调用
p.aa();
3.上面是 原型方法aa 调用
Person.prototype.aa();
4.上面是“Person.prototype.***”调用


Person.call(document);
5.上面是普通函数调用
Person.call(Person);
6.上面是普通函数调用
Person.call(p);
7.上面是 原型方法aa 调用


Person.prototype = { };
var p = new Person();
8.上面是new Person() 调用
p.aa = Person;
p.aa();
9.上面是 扩展属性aa 调用


Person.prototype = {aa:Person};
var p = new Person();
10.上面是new Person() 调用
p.aa();
11.上面是 原型方法aa★★ 调用
Person.prototype.aa();
12.上面是“Person.prototype.***”调用▲▲▲


var p = new Person();
13.上面是new Person() 调用
p.fn = Person;
p.haha = Person;
p.fn();
14.上面可能是 原型方法bb★★原型方法aa★★扩展属性fn扩展属性haha 调用


Person.hello = Person;
Person.hello();
15.上面是普通函数调用
Person.hello.hello.hello.hello.hello.hello.hello.hello.hello();
16.上面是普通函数调用
new Person.hello();
17.上面是new Person() 调用
new Person.hello.hello.hello.hello.hello.hello.hello.hello.hello();
18.上面是new Person() 调用


eval(Person.toString().replace('Person','B'));
new B();
19.上面是new B() 调用

///

源代码:

posted @ 2022-11-23 21:10  IginCui  阅读(50)  评论(0编辑  收藏  举报