定义和用法
constructor 属性返回对创建此对象的数组函数的引用。
语法
object.constructor
实例
例子 1
在本例中,我们将展示如何使用 constructor 属性:
<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>输出:
立即学习“Java免费学习笔记(深入)”;
This is an Array
例子 2
在本例中,我们将展示如何使用 constructor 属性:
<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>输出:
立即学习“Java免费学习笔记(深入)”;
function employee(name, job, born)
{this.name = name; this.job = job; this.born = born;}示例&说明
以下代码中的[native code],表示这是JavaScript的底层内部代码实现,无法显示代码细节。
// 字符串: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 去修改或扩展原型对象
以上就是JavaScript返回对创建此对象的数组函数的引用属性constructor的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号