首頁 > web前端 > js教程 > 主體

JavaScript傳回對建立此物件的Date函數所引用的屬性constructor

黄舟
發布: 2017-11-04 13:55:48
原創
2256 人瀏覽過

定義和用法

constructor 屬性傳回對建立此物件的 Date 函數的參考。

語法

object.constructor
登入後複製

實例

在本例中,我們將展示如何使用constructor 屬性:

<script type="text/javascript">

var test=new Date();

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>
登入後複製

輸出:

This is a Date
登入後複製

範例&說明

以下程式碼中的[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傳回對建立此物件的Date函數所引用的屬性constructor的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!