JavaScript constructor 属性详解

对象的constructor属性用于返回创建该对象的函数,也就是我们常说的构造函数。

在JavaScript中,每个具有原型的对象都会自动获得constructor属性。除了arguments、Enumerator、Error、Global、Math、RegExp、Regular Expression等一些特殊对象之外,其他所有的JavaScript内置对象都具备constructor属性。例如:Array、Boolean、Date、Function、Number、Object、String等。

 

语法

Object.constructor

 

返回值

对象的constructor属性返回创建该对象的函数的引用。

 

 

示例&说明

以下代码中的[native code],表示这是JavaScript的底层内部代码实现,无法显示代码细节。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

// 字符串:String()

var str = "张三";

alert(str.constructor); // function String() { [native code] }

alert(str.constructor === String); // true

 

// 数组:Array()

var arr = [1, 2, 3];

alert(arr.constructor); // function Array() { [native code] }

alert(arr.constructor === Array); // true

 

// 数字:Number()

var num = 5;

alert(num.constructor); // function Number() { [native code] }

alert(num.constructor === Number); // true

 

// 自定义对象:Person()

function Person(){

    this.name = "CodePlayer";

}

var p = new Person();

alert(p.constructor); // function Person(){ this.name = "CodePlayer"; }

alert(p.constructor === Person); // true

 

// JSON对象:Object()

var o = { "name" : "张三"};

alert(o.constructor); // function Object() { [native code] }

alert(o.constructor === Object); // true

 

// 自定义函数:Function()

function foo(){

    alert("CodePlayer");

}

alert(foo.constructor); // function Function() { [native code] }

alert(foo.constructor === Function); // true

 

// 函数的原型:bar()

function bar(){

    alert("CodePlayer");

}

alert(bar.prototype.constructor); // function bar(){ alert("CodePlayer"); }

alert(bar.prototype.constructor === bar); // true

 

为了将实例的构造器的原型对象暴露出来, 比如你写了一个插件,别人得到的都是你实例化后的对象, 如果别人想扩展下对象,就可以用 instance.constructor.prototype 去修改或扩展原型对象


链接:https://www.zhihu.com/question/19951896/answer/67551712

引用 javascript 对象中的 constructor属性的作用?的回答:

var a,b;
(function(){
  function A (arg1,arg2) {
    this.a = 1;
    this.b=2; 
  }

  A.prototype.log = function () {
    console.log(this.a);
  }
  a = new A();
  b = new A();
})()
a.log();
// 1
b.log();
// 1

通过以上代码我们可以得到两个对象,a,b,他们同为类A的实例。因为A在闭包里,所以现在我们是不能直接访问A的,那如果我想给类A增加新方法怎么办?

// a.constructor.prototype 在chrome,firefox中可以通过 a.__proto__ 直接访问
a.constructor.prototype.log2 = function () {
  console.log(this.b)
}

a.log2();
// 2
b.log2();
// 2

通过访问constructor就可以了。
或者我想知道a的构造函数有几个参数?

a.constructor.length

或者再复杂点,我想知道a的构造函数的参数名是什么(angular的依赖注入就是通过此方法实现的据说)

a.constructor
 .toString()
 .match(/\(.*\)/)
 .pop().slice(1,-1)
 .split(',');
// ["arg1", "arg2"]
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值