Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Object.prototype.constructor

この記事は技術レビューを必要としています。ぜひご協力ください

この記事は編集レビューを必要としています。ぜひご協力ください

概要

インスタンスのプロトタイプをつくったObject関数の参照を返します。ご注意いただきたいのは、このプロパティの値は、関数そのものの参照だということです。関数の名前が含まれた文字列ではありません。1true、あるいは"test"などのプリミティブ値については、このプロパティ値は読み取り専用です。

説明

すべてのオブジェクトは、constructorプロパティをprototypeから継承します。

var o = {};
o.constructor === Object; // true

var a = [];
a.constructor === Array; // true

var n = new Number(3);
n.constructor === Number; // true

例: オブジェクトのコンストラクタを表示する

つぎの例は、Treeのプロトタイプとその型のオブジェクトtheTreeをつくります。そして、オブジェクトtheTreeconstructorプロパティを表示します。

function Tree(name) {
  this.name = name;
}

var theTree = new Tree('Redwood');
console.log('theTree.constructor is ' + theTree.constructor);

This example displays the following output:

この例の出力はつぎのとおりです。

theTree.constructor is function Tree(name) {
  this.name = name;
}

例: オブジェクトのconstructorを変える

つぎの例は、一般的なオブジェクトのconstructorの値はどのようにして変えたらよいのかを示します。true1、および"test"だけは、値が読み取り専用のネイティブのため書き替わりません。したがって、constructorプロパティにつねに頼ってよいとはかぎりません。

function Type () {}

var types = [
  new Array(),
  [],
  new Boolean(),
  true,             // 変わらない
  new Date(),
  new Error(),
  new Function(),
  function () {},
  Math,
  new Number(),
  1,                // 変わらない
  new Object(),
  {},
  new RegExp(),
  /(?:)/,
  new String(),
  'test'            // 変わらない
];

for (var i = 0; i < types.length; i++) {
  types[i].constructor = Type;
  types[i] = [types[i].constructor, types[i] instanceof Type, types[i].toString()];
}

console.log(types.join('\n'));

この例の出力はつぎのとおりです。

function Type() {},false,
function Type() {},false,
function Type() {},false,false
function Boolean() {
    [native code]
},false,true
function Type() {},false,Mon Sep 01 2014 16:03:49 GMT+0600
function Type() {},false,Error
function Type() {},false,function anonymous() {

}
function Type() {},false,function () {}
function Type() {},false,[object Math]
function Type() {},false,0
function Number() {
    [native code]
},false,1
function Type() {},false,[object Object]
function Type() {},false,[object Object]
function Type() {},false,/(?:)/
function Type() {},false,/(?:)/
function Type() {},false,
function String() {
    [native code]
},false,test

仕様

仕様 状況 コメント
ECMAScript 1st Edition. Standard 初期定義。JavaScript 1.1による実装。
ECMAScript 5.1 (ECMA-262)
The definition of 'Object.prototype.constructor' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Object.prototype.constructor' in that specification.
Standard  

ブラウザの互換性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (有) (有) (有) (有) (有)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (有) (有) (有) (有) (有) (有)

ドキュメントのタグと貢献者

 このページの貢献者: FumioNonaka, shide55
 最終更新者: FumioNonaka,