Home > Article > Web Front-end > JavaScript returns a reference to the array function that created this object. Property constructor
Definition and Usage
The constructor property returns a reference to the array function that created this object.
Syntax
object.constructor
Examples
Example 1
In this example, we will show how to use the constructor attribute:
<script type="text/javascript"> var test=new Array(); if (test.constructor==Array) { document.write("This is an Array"); } if (test.constructor==Boolean) { document.write("This is a Boolean"); } if (test.constructor==Date) { document.write("This is a Date"); } if (test.constructor==String) { document.write("This is a String"); } </script>
Output :
This is an Array
Example 2
In this example, we will show how to use the constructor attribute:
<script type="text/javascript"> function employee(name,job,born) { this.name=name; this.job=job; this.born=born; } var bill=new employee("Bill Gates","Engineer",1985); document.write(bill.constructor); </script>
Output:
function employee(name, job, born) {this.name = name; this.job = job; this.born = born;}
Example & Description
[native code] in the following code indicates that this is the underlying internal code implementation of JavaScript, and code details cannot be displayed.
// 字符串: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
In order to expose the prototype object of the instance constructor, for example, if you write a plug-in, others will get the object you instantiated. If others want to extend the object, they can use instance. constructor.prototype to modify or extend the prototype object
The above is the detailed content of JavaScript returns a reference to the array function that created this object. Property constructor. For more information, please follow other related articles on the PHP Chinese website!