From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../global_objects/object/assign/index.html | 249 ++++++++++++++ .../global_objects/object/create/index.html | 258 ++++++++++++++ .../object/defineproperties/index.html | 224 ++++++++++++ .../object/defineproperty/index.html | 380 +++++++++++++++++++++ .../global_objects/object/freeze/index.html | 198 +++++++++++ .../object/getprototypeof/index.html | 128 +++++++ .../object/hasownproperty/index.html | 184 ++++++++++ .../reference/global_objects/object/index.html | 222 ++++++++++++ .../global_objects/object/keys/index.html | 208 +++++++++++ .../object/preventextensions/index.html | 179 ++++++++++ .../global_objects/object/proto/index.html | 137 ++++++++ .../global_objects/object/prototype/index.html | 218 ++++++++++++ .../global_objects/object/watch/index.html | 191 +++++++++++ 13 files changed, 2776 insertions(+) create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/create/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html (limited to 'files/zh-tw/web/javascript/reference/global_objects/object') diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..f4dfca5af7 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,249 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +
{{JSRef}}
+ +
Object.assign()被用來複製一個或多個物件自身所有可數的屬性到另一個目標物件。回傳的值為該目標物件。
+ +

語法

+ +
Object.assign(target, ...sources)
+ +

參數

+ +
+
target
+
目標物件
+
sources
+
來源物件
+
+ +

回傳值

+ +

     合併目標物件及(多個)來源物件所得到的最終物件。

+ +

說明

+ +

如果在目標物件裡的屬性名稱(key)和來源物件的屬性名稱相同,將會被覆寫。若來源物件之間又有相同的屬性名稱,則後者會將前者覆寫。

+ +

Object.assign()只會從來源物件將自身可列舉的屬性複製到目標物件。此函式方法(method) 使用來源物件的[[Get]]事件和目標物件的[[Set]]事件,使它將會執行getters和setters。因此,這邊的指派(assigns)屬性不只是複製或定義新屬性。若在合併包含getters的來源物件時,這個事件可能就不適合用來合併屬性。至於複製屬性的定義(包含其可列舉性)到各屬性,反倒是會用到 {{jsxref("Object.getOwnPropertyDescriptor()")}} 和 {{jsxref("Object.defineProperty()")}} 。

+ +

{{jsxref("String")}} 和 {{jsxref("Symbol")}} 類型的屬性都會被複製。

+ +

若發生錯誤,例如: 當一個屬性不可被寫入時,將會引發 {{jsxref("TypeError")}} 的錯誤,且目標物件剩餘的屬性將不會改變。

+ +

注意: Object.assign() 不會在來源物件屬性的值為{{jsxref("null")}} 或 {{jsxref("undefined")}} 的時候拋出錯誤。

+ +

範例

+ +

複製物件

+ +
var obj = { a: 1 };
+var copy = Object.assign({}, obj);
+console.log(copy); // { a: 1 }
+
+ +

警告:非深層複製

+ +

深層複製(deep clone)需要使用其他的替代方案,因為 Object.assign() 僅複製屬性值。若來源物件的值參照到一個子物件,它只會複製該子物件的參照。

+ +
function test() {
+  let a = { b: {c:4} , d: { e: {f:1}} }
+  let g = Object.assign({},a) // 淺層
+  let h = JSON.parse(JSON.stringify(a)); // 深層
+  console.log(g.d) // { e: { f: 1 } }
+  g.d.e = 32
+  console.log('g.d.e set to 32.') // g.d.e set to 32.
+  console.log(g) // { b: { c: 4 }, d: { e: 32 } }
+  console.log(a) // { b: { c: 4 }, d: { e: 32 } }
+  console.log(h) // { b: { c: 4 }, d: { e: { f: 1 } } }
+  h.d.e = 54
+  console.log('h.d.e set to 54.') // h.d.e set to 54.
+  console.log(g) // { b: { c: 4 }, d: { e: 32 } }
+  console.log(a) // { b: { c: 4 }, d: { e: 32 } }
+  console.log(h) // { b: { c: 4 }, d: { e: 54 } }
+}
+test();
+
+ +

合併物件

+ +
var o1 = { a: 1 };
+var o2 = { b: 2 };
+var o3 = { c: 3 };
+
+var obj = Object.assign(o1, o2, o3);
+console.log(obj); // { a: 1, b: 2, c: 3 }
+console.log(o1);  // { a: 1, b: 2, c: 3 }, 目標物件本身也被改變。
+ +

有相同屬性時合併物件

+ +
var o1 = { a: 1, b: 1, c: 1 };
+var o2 = { b: 2, c: 2 };
+var o3 = { c: 3 };
+
+var obj = Object.assign({}, o1, o2, o3);
+console.log(obj); // { a: 1, b: 2, c: 3 },屬性c為o3.c的值,最後一個出現的屬性c。
+ +

所有的屬性會被後方相同屬性名稱的值覆寫。

+ +

複製 Symbol 型別的屬性

+ +
var o1 = { a: 1 };
+var o2 = { [Symbol('foo')]: 2 };
+
+var obj = Object.assign({}, o1, o2);
+console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
+Object.getOwnPropertySymbols(obj); // [Symbol(foo)]非不在
+
+ +

在屬性鏈中的不可列舉屬性不會被複製

+ +
var obj = Object.create({ foo: 1 }, { // foo 是 obj 的屬性鏈。
+  bar: {
+    value: 2  // bar 是不可列舉的屬性,因為enumerable預設為false。
+  },
+  baz: {
+    value: 3,
+    enumerable: true  // baz 是自身可列舉的屬性。
+  }
+});
+
+var copy = Object.assign({}, obj);
+console.log(copy); // { baz: 3 }
+
+ +

原始型別會被包成物件

+ +
var v1 = 'abc';
+var v2 = true;
+var v3 = 10;
+var v4 = Symbol('foo');
+
+var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
+// 原始型別會被打包,null和undefined則會被忽略。
+// 注意: 只有打包成物件的字串是可列舉的,即可被複製的。
+console.log(obj); // { "0": "a", "1": "b", "2": "c" }
+
+ +

任何異常將會中斷正進行的複製程序

+ +
var target = Object.defineProperty({}, 'foo', {
+  value: 1,
+  writable: false
+}); // target.foo 是 read-only (唯讀)屬性
+
+Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
+// TypeError: "foo" 是 read-only
+// 在指派值給 target.foo 時,異常(Exception)會被拋出。
+
+console.log(target.bar);  // 2, 第一個來源物件複製成功。
+console.log(target.foo2); // 3, 第二個來源物件的第一個屬性複製成功。
+console.log(target.foo);  // 1, 異常在這裡拋出。
+console.log(target.foo3); // undefined, 複製程式已中斷,複製失敗。
+console.log(target.baz);  // undefined, 第三個來源物件也不會被複製。
+
+ +

複製的存取程序

+ +
var obj = {
+  foo: 1,
+  get bar() {
+    return 2;
+  }
+};
+
+var copy = Object.assign({}, obj);
+console.log(copy);
+// { foo: 1, bar: 2 }, copy.bar的值,是obj.bar的getter回傳的值。
+
+// 這個函式用來複製完整的描述內容。
+function completeAssign(target, ...sources) {
+  sources.forEach(source => {
+    let descriptors = Object.keys(source).reduce((descriptors, key) => {
+      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
+      return descriptors;
+    }, {});
+    // Object.assign 預設會複製可列舉的Symbols。
+    Object.getOwnPropertySymbols(source).forEach(sym => {
+      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
+      if (descriptor.enumerable) {
+        descriptors[sym] = descriptor;
+      }
+    });
+    Object.defineProperties(target, descriptors);
+  });
+  return target;
+}
+
+var copy = completeAssign({}, obj);
+console.log(copy);
+// { foo:1, get bar() { return 2 } }
+
+ +

Polyfill

+ +

{{Glossary("Polyfill","polyfill")}} 不支援Symbol屬性,因為ES5沒有Symbol型別。

+ +
if (typeof Object.assign != 'function') {
+  Object.assign = function (target, varArgs) { // .length of function is 2
+    'use strict';
+    if (target == null) { // TypeError if undefined or null
+      throw new TypeError('Cannot convert undefined or null to object');
+    }
+
+    var to = Object(target);
+
+    for (var index = 1; index < arguments.length; index++) {
+      var nextSource = arguments[index];
+
+      if (nextSource != null) { // Skip over if undefined or null
+        for (var nextKey in nextSource) {
+          // Avoid bugs when hasOwnProperty is shadowed
+          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
+            to[nextKey] = nextSource[nextKey];
+          }
+        }
+      }
+    }
+    return to;
+  };
+}
+
+ +

規格

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-object.assign', 'Object.assign')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ +
{{Compat("javascript.builtins.Object.assign")}}
+ +
+ +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/create/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/create/index.html new file mode 100644 index 0000000000..f158d36977 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/create/index.html @@ -0,0 +1,258 @@ +--- +title: Object.create() +slug: Web/JavaScript/Reference/Global_Objects/Object/create +translation_of: Web/JavaScript/Reference/Global_Objects/Object/create +--- +
{{JSRef}}
+ +

Object.create() 指定其原型物件與屬性,創建一個新物件。

+ +

語法

+ +
Object.create(proto[, propertiesObject])
+ +

參數

+ +
+
proto
+
指定新物件的原型 (prototype) 物件。
+
propertiesObject
+
選用,為一物件。如有指定且非 {{jsxref("undefined")}},則此參數物件中可列舉出的屬性 (即參數物件自身定義的屬性,並非指原型鏈上的 enumerable 特性 ) 對應其屬性名稱,根據其屬性敘述元 (property descriptors) 加進新創建的物件。這些屬性對應到 {{jsxref("Object.defineProperties()")}} 的第二個參數。
+
+ +

回傳

+ +

具有指定原型物件與屬性的新物件。

+ +

例外

+ +

 如果 proto 參數不是 {{jsxref("null")}} 或一個物件,將會拋出 {{jsxref("TypeError")}} 例外。

+ +

範例

+ +

使用 Object.create() 實現類別繼承

+ +

下方是如何使用 Object.create() 去實現類別繼承的示範,此為 JavaScript 支援的單一繼承.。

+ +
// Shape - 父類別
+function Shape() {
+  this.x = 0;
+  this.y = 0;
+}
+
+// 父類別的方法
+Shape.prototype.move = function(x, y) {
+  this.x += x;
+  this.y += y;
+  console.info('Shape moved.');
+};
+
+// Rectangle - 子類別
+function Rectangle() {
+  Shape.call(this); // call super constructor.
+}
+
+// 子類別擴展(extends)父類別
+Rectangle.prototype = Object.create(Shape.prototype);
+Rectangle.prototype.constructor = Rectangle;
+
+var rect = new Rectangle();
+
+console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
+console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
+rect.move(1, 1); // Outputs, 'Shape moved.'
+
+ +

也可像 mixin 繼承多個物件。

+ +
function MyClass() {
+  SuperClass.call(this);
+  OtherSuperClass.call(this);
+}
+
+// 繼承一個父類別
+MyClass.prototype = Object.create(SuperClass.prototype);
+// mixin另一個父類別
+Object.assign(MyClass.prototype, OtherSuperClass.prototype);
+// 重新指定建構式
+MyClass.prototype.constructor = MyClass;
+
+MyClass.prototype.myMethod = function() {
+  // do a thing
+};
+
+ +

Object.assign 複製 OtherSuperClass 原型上的所有屬性到 MyClass 的原型上,使所有 MyClass 的實例都能使用。Object.assign 為 ES2015 標準且有 polyfill。如需支援較舊的瀏覽器,可使用第三方套件實現如 jQuery.extend() 或 _.assign() 。

+ +

propertiesObject 參數的使用

+ +
var o;
+
+// 建立以null為原型的物件
+o = Object.create(null);
+
+
+o = {};
+// 等同於:
+o = Object.create(Object.prototype);
+
+
+// Example where we create an object with a couple of sample properties.
+// (Note that the second parameter maps keys to *property descriptors*.)
+o = Object.create(Object.prototype, {
+  // foo 為數值屬性
+  foo: { writable: true, configurable: true, value: 'hello' },
+  // bar 為 getter-and-setter 訪問屬性
+  bar: {
+    configurable: false,
+    get: function() { return 10; },
+    set: function(value) { console.log('Setting `o.bar` to', value); }
+/* with ES5 Accessors our code can look like this
+    get function() { return 10; },
+    set function(value) { console.log('setting `o.bar` to', value); } */
+  }
+});
+
+
+function Constructor() {}
+o = new Constructor();
+// 等同於:
+o = Object.create(Constructor.prototype);
+// Of course, if there is actual initialization code in the
+// Constructor function, the Object.create() cannot reflect it
+
+
+// 創建一個新物件,指定原型是全新的空物件,並加入值為 42 的屬性'p'
+o = Object.create({}, { p: { value: 42 } });
+
+// 屬性敘述元 writable, enumerable , configurable 未定義,預設皆為 false
+o.p = 24;
+o.p;
+// 42
+
+o.q = 12;
+for (var prop in o) {
+  console.log(prop);
+}
+// 'q'
+
+delete o.p;
+// false
+
+// to specify an ES3 property
+o2 = Object.create({}, {
+  p: {
+    value: 42,
+    writable: true,
+    enumerable: true,
+    configurable: true
+  }
+});
+
+ +

Polyfill

+ +

此 polyfill 涵蓋了主要的使用情境:指定一個原型創建一個新的物件,第二個參數為選用。

+ +

要注意的是在 ES5 的Object.create中, [[Prototype]] 可以為 null,但在ECMAScript 5 以前的版本,polyfill 會因為繼承限制( limitation inherent )而不支援此情形。

+ +
if (typeof Object.create !== "function") {
+    Object.create = function (proto, propertiesObject) {
+        if (!(proto === null || typeof proto === "object" || typeof proto === "function")) {
+            throw TypeError('Argument must be an object, or null');
+        }
+        var temp = new Object();
+        temp.__proto__ = proto;
+        if(typeof propertiesObject === "object")
+            Object.defineProperties(temp, propertiesObject);
+        return temp;
+    };
+}
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.create', 'Object.create')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.create', 'Object.create')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}{{CompatVersionUnknown}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
+
+ +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html new file mode 100644 index 0000000000..fc87ca0317 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html @@ -0,0 +1,224 @@ +--- +title: Object.defineProperties() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +--- +
{{JSRef}}
+ +

Object.defineProperties() 函式可定義新的或是修改已存在的物件屬性,並回傳修改後的物件。

+ +

語法

+ +
Object.defineProperties(obj, props)
+ +

參數

+ +
+
obj
+
The object on which to define or modify properties.
+
props
+
An object whose own enumerable properties constitute descriptors for the properties to be defined or modified. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors (see {{jsxref("Object.defineProperty()")}} for more details). Descriptors have the following keys:
+
+
+
configurable
+
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
+ 預設為 false.
+
enumerable
+
若該屬性設為 true,則該屬性可被物件所列舉。
+ 預設為 false.
+
+ +
+
value
+
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
+ 預設為 {{jsxref("undefined")}}.
+
writable
+
若該屬性為 true,則該屬性可透過{{jsxref("Operators/Assignment_Operators", "賦予運算子", "", 1)}}所改變
+ 預設為 false.
+
+ +
+
get
+
A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. The function return will be used as the value of property.
+ 預設為 {{jsxref("undefined")}}.
+
set
+
A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. The function will receive as only argument the new value being assigned to the property.
+ 預設為 {{jsxref("undefined")}}.
+
+
+
+ +

回傳值

+ +

The object that was passed to the function.

+ +

描述

+ +

Object.defineProperties, in essence, defines all properties corresponding to the enumerable own properties of props on the object obj object.

+ +

範例

+ +
var obj = {};
+Object.defineProperties(obj, {
+  'property1': {
+    value: true,
+    writable: true
+  },
+  'property2': {
+    value: 'Hello',
+    writable: false
+  }
+  // etc. etc.
+});
+
+ +

Polyfill

+ +

Assuming a pristine execution environment with all names and properties referring to their initial values, Object.defineProperties is almost completely equivalent (note the comment in isCallable) to the following reimplementation in JavaScript:

+ +
function defineProperties(obj, properties) {
+  function convertToDescriptor(desc) {
+    function hasProperty(obj, prop) {
+      return Object.prototype.hasOwnProperty.call(obj, prop);
+    }
+
+    function isCallable(v) {
+      // NB: modify as necessary if other values than functions are callable.
+      return typeof v === 'function';
+    }
+
+    if (typeof desc !== 'object' || desc === null)
+      throw new TypeError('bad desc');
+
+    var d = {};
+
+    if (hasProperty(desc, 'enumerable'))
+      d.enumerable = !!desc.enumerable;
+    if (hasProperty(desc, 'configurable'))
+      d.configurable = !!desc.configurable;
+    if (hasProperty(desc, 'value'))
+      d.value = desc.value;
+    if (hasProperty(desc, 'writable'))
+      d.writable = !!desc.writable;
+    if (hasProperty(desc, 'get')) {
+      var g = desc.get;
+
+      if (!isCallable(g) && typeof g !== 'undefined')
+        throw new TypeError('bad get');
+      d.get = g;
+    }
+    if (hasProperty(desc, 'set')) {
+      var s = desc.set;
+      if (!isCallable(s) && typeof s !== 'undefined')
+        throw new TypeError('bad set');
+      d.set = s;
+    }
+
+    if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d))
+      throw new TypeError('identity-confused descriptor');
+
+    return d;
+  }
+
+  if (typeof obj !== 'object' || obj === null)
+    throw new TypeError('bad obj');
+
+  properties = Object(properties);
+
+  var keys = Object.keys(properties);
+  var descs = [];
+
+  for (var i = 0; i < keys.length; i++)
+    descs.push([keys[i], convertToDescriptor(properties[keys[i]])]);
+
+  for (var i = 0; i < descs.length; i++)
+    Object.defineProperty(obj, descs[i][0], descs[i][1]);
+
+  return obj;
+}
+
+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatus註記
{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5
{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2")}}{{CompatChrome("5")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
+
+ +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html new file mode 100644 index 0000000000..cf83590181 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html @@ -0,0 +1,380 @@ +--- +title: Object.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +--- +
{{JSRef}}
+ +

靜態方法 Object.defineProperty() 會直接對一個物件定義、或是修改現有的屬性。執行後會回傳定義完的物件。

+ +
+

注:這個方法會直接針對 {{jsxref("Object")}} 呼叫建構子(constructor),而不是 Object 型別的實例。

+
+ +
{{EmbedInteractiveExample("pages/js/object-defineproperty.html")}}
+ +

語法

+ +
Object.defineProperty(obj, prop, descriptor)
+ +

參數

+ +
+
obj
+
要定義屬性的物件。
+
prop
+
要被定義或修改的屬性名字。
+
descriptor
+
要定義或修改物件敘述內容。
+
+ +

回傳值

+ +

被定義完或修改完屬性的物件。

+ +

描述

+ +

這個函式可以用來增加或修改物件中的屬性定義。在物件建立屬性後,這些屬性同時有被設定預設的設定,才能讓這些屬性被列舉、改變和刪除。而這個函式可以用來改變這些預設的設定。根據預設,被加到物件且使用Object.defineProperty()的值都是{{glossary("Immutable")}}。

+ +

物件內的屬性描述器(Property descriptor)主要有兩種:資料描述器(data descriptor)與訪問描述器(accessor descriptor)。資料描述器(data descriptor)是可以選擇能否覆寫的屬性。訪問描述器(accessor descriptor) is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

+ +

data 和 accessor descriptors 皆為物件,兩者共享下面提及的 key:

+ +
+
configurable
+
true 則若且唯若此屬性則將可改變或刪除自相應物件。
+ 預設為 false
+
enumerable
+
true 如果且唯若相應物件被列舉,將會列舉此屬性。
+ 預設為 false
+
+ +

一個 data descriptor 還有以下可選的 key:

+ +
+
value
+
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
+ 預設 {{jsxref("undefined")}}.
+
writable
+
true 則該物件屬性可透過{{jsxref("Operators/Assignment_Operators", "賦予運算子", "", 1)}}改變其值。
+ 預設 false
+
+ +

一個 accessor descriptor 也擁有下述之 optional keys:

+ +
+
get
+
作為 getter 形式,為屬性存在的函式,如果沒有 getter 的話則回傳 {{jsxref("undefined")}}。函式回傳將用於屬性值。
+ 預設 {{jsxref("undefined")}}
+
set
+
作為 setter 形式,為屬性存在的函式,如果沒有 setter 的話則回傳 {{jsxref("undefined")}}。 The function will receive as only argument the new value being assigned to the property.
+ 預設 {{jsxref("undefined")}}
+
+ +

請注意,這些選項並不一定要是 descriptor 屬性,由原型鍊(prototype chain)繼承的屬性,也會被考慮到。要確保需要凍結(freeze)的 {{jsxref("Object.prototype")}} upfront 預設能被保存,請明確指定所有選項,或把 {{jsxref("Object.prototype.__proto__", "__proto__")}} 屬性指向 {{jsxref("null")}}。

+ +
// using __proto__
+var obj = {};
+Object.defineProperty(obj, 'key', {
+  __proto__: null, // no inherited properties
+  value: 'static'  // not enumerable
+                   // not configurable
+                   // not writable
+                   // as defaults
+});
+
+// being explicit
+Object.defineProperty(obj, 'key', {
+  enumerable: false,
+  configurable: false,
+  writable: false,
+  value: 'static'
+});
+
+// recycling same object
+function withValue(value) {
+  var d = withValue.d || (
+    withValue.d = {
+      enumerable: false,
+      writable: false,
+      configurable: false,
+      value: null
+    }
+  );
+  d.value = value;
+  return d;
+}
+// ... and ...
+Object.defineProperty(obj, 'key', withValue('static'));
+
+// if freeze is available, prevents adding or
+// removing the object prototype properties
+// (value, get, set, enumerable, writable, configurable)
+(Object.freeze || Object)(Object.prototype);
+
+ +

範例

+ +

If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see additional examples.

+ +

建立屬性

+ +

When the property specified doesn't exist in the object, Object.defineProperty() creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are imputed. All of the Boolean-valued fields default to false. The value, get, and set fields default to {{jsxref("undefined")}}. A property which is defined without get/set/value/writable is called “generic” and is “typed” as a data descriptor.

+ +
var o = {}; // Creates a new object
+
+// Example of an object property added with defineProperty with a data property descriptor
+Object.defineProperty(o, 'a', {
+  value: 37,
+  writable: true,
+  enumerable: true,
+  configurable: true
+});
+// 'a' property exists in the o object and its value is 37
+
+// Example of an object property added with defineProperty with an accessor property descriptor
+var bValue = 38;
+Object.defineProperty(o, 'b', {
+  get: function() { return bValue; },
+  set: function(newValue) { bValue = newValue; },
+  enumerable: true,
+  configurable: true
+});
+o.b; // 38
+// 'b' property exists in the o object and its value is 38
+// The value of o.b is now always identical to bValue, unless o.b is redefined
+
+// You cannot try to mix both:
+Object.defineProperty(o, 'conflict', {
+  value: 0x9f91102,
+  get: function() { return 0xdeadbeef; }
+});
+// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
+
+ +

修改屬性

+ +

如果該屬性已經存在, Object.defineProperty() 將會根據描述符內的值和物件當前的 configuration 來修改屬性。 如果舊的描述符之 configurable 的特徵為 false (屬性為 “non-configurable”), 那除了 writable 之外的特徵都將無法修改。 在這個情況,也不可能在 data 和 accessor 屬性類型中來回切換。

+ +

如果有一個屬性是 non-configurable, 那它的 writable 特徵只能被改變為 false.

+ +

若嘗試改變 non-configurable property attributes,將會丟出一個 {{jsxref("TypeError")}},除非當前之值與新值相同。

+ +

Writable attribute

+ +

當 writable 屬性特徵被設為 false, 此屬性為 “non-writable”. 它將無法被重新賦值。

+ +
var o = {}; // Creates a new object
+
+Object.defineProperty(o, 'a', {
+  value: 37,
+  writable: false
+});
+
+console.log(o.a); // logs 37
+o.a = 25; // No error thrown (it would throw in strict mode, even if the value had been the same)
+console.log(o.a); // logs 37. The assignment didn't work.
+
+ +

As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.

+ +

可列舉 attribute

+ +

The enumerable property attribute defines whether the property shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not.

+ +
var o = {};
+Object.defineProperty(o, 'a', { value: 1, enumerable: true });
+Object.defineProperty(o, 'b', { value: 2, enumerable: false });
+Object.defineProperty(o, 'c', { value: 3 }); // enumerable defaults to false
+o.d = 4; // enumerable defaults to true when creating a property by setting it
+
+for (var i in o) {
+  console.log(i);
+}
+// logs 'a' and 'd' (in undefined order)
+
+Object.keys(o); // ['a', 'd']
+
+o.propertyIsEnumerable('a'); // true
+o.propertyIsEnumerable('b'); // false
+o.propertyIsEnumerable('c'); // false
+
+ +

可設定 attribute

+ +

The configurable attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than writable) can be changed.

+ +
var o = {};
+Object.defineProperty(o, 'a', {
+  get: function() { return 1; },
+  configurable: false
+});
+
+Object.defineProperty(o, 'a', { configurable: true }); // throws a TypeError
+Object.defineProperty(o, 'a', { enumerable: true }); // throws a TypeError
+Object.defineProperty(o, 'a', { set: function() {} }); // throws a TypeError (set was undefined previously)
+Object.defineProperty(o, 'a', { get: function() { return 1; } }); // throws a TypeError (even though the new get does exactly the same thing)
+Object.defineProperty(o, 'a', { value: 12 }); // throws a TypeError
+
+console.log(o.a); // logs 1
+delete o.a; // Nothing happens
+console.log(o.a); // logs 1
+
+ +

If the configurable attribute of o.a had been true, none of the errors would be thrown and the property would be deleted at the end.

+ +

新增多個屬性及賦予初始值

+ +

It's important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using Object.defineProperty(), as shown in the example below.

+ +
var o = {};
+
+o.a = 1;
+// is equivalent to:
+Object.defineProperty(o, 'a', {
+  value: 1,
+  writable: true,
+  configurable: true,
+  enumerable: true
+});
+
+
+// On the other hand,
+Object.defineProperty(o, 'a', { value: 1 });
+// is equivalent to:
+Object.defineProperty(o, 'a', {
+  value: 1,
+  writable: false,
+  configurable: false,
+  enumerable: false
+});
+
+ +

Custom Setters and Getters

+ +

Example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

+ +
function Archiver() {
+  var temperature = null;
+  var archive = [];
+
+  Object.defineProperty(this, 'temperature', {
+    get: function() {
+      console.log('get!');
+      return temperature;
+    },
+    set: function(value) {
+      temperature = value;
+      archive.push({ val: temperature });
+    }
+  });
+
+  this.getArchive = function() { return archive; };
+}
+
+var arc = new Archiver();
+arc.temperature; // 'get!'
+arc.temperature = 11;
+arc.temperature = 13;
+arc.getArchive(); // [{ val: 11 }, { val: 13 }]
+
+ +

or

+ +
var pattern = {
+    get: function () {
+        return 'I always return this string, whatever you have assigned';
+    },
+    set: function () {
+        this.myname = 'this is my name string';
+    }
+};
+
+
+function TestDefineSetAndGet() {
+    Object.defineProperty(this, 'myproperty', pattern);
+}
+
+
+var instance = new TestDefineSetAndGet();
+instance.myproperty = 'test';
+console.log(instance.myproperty); // I always return this string, whatever you have assigned
+
+console.log(instance.myname); // this is my name string
+
+
+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatus註記
{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Object.defineProperty")}}

+
+ +

Compatibility notes

+ +

Redefining the length property of an Array object

+ +

It is possible to redefine the {{jsxref("Array.length", "length")}} property of arrays, subject to the usual redefinition restrictions. (The {{jsxref("Array.length", "length")}} property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array, it's possible to change the {{jsxref("Array.length", "length")}} property's value or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.

+ +

Firefox 4 through 22 will throw a {{jsxref("TypeError")}} on any attempt whatsoever (whether permitted or not) to redefine the {{jsxref("Array.length", "length")}} property of an array.

+ +

Versions of Chrome which implement Object.defineProperty() in some circumstances ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like {{jsxref("Array.prototype.push")}} don't respect a non-writable length.

+ +

Versions of Safari which implement Object.defineProperty() ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property, and attempts to change writability execute without error but do not actually change the property's writability.

+ +

Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the {{jsxref("Array.length", "length")}} property of arrays. For now, don't rely on redefining the {{jsxref("Array.length", "length")}} property of an array to either work, or to work in a particular manner. And even when you can rely on it, there's really no good reason to do so.

+ +

Internet Explorer 8 specific notes

+ +

Internet Explorer 8 implemented a Object.defineProperty() method that could only be used on DOM objects. A few things need to be noted:

+ + + +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html new file mode 100644 index 0000000000..0c26b9f308 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html @@ -0,0 +1,198 @@ +--- +title: Object.freeze() +slug: Web/JavaScript/Reference/Global_Objects/Object/freeze +translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze +--- +
{{JSRef}}
+ +

 

+ +

Object.freeze() 顧名思義是用來「凍結」一個物件的: 也就是防止物件新增屬性; 防止物件既有的屬性被刪除; 防止物件原本的屬性, 還有屬性的可列舉性, 可設定性, 可寫性被改動; 同時它也防止物件的原型被改變。此方法回傳一個凍結狀態的物件。

+ +
{{EmbedInteractiveExample("pages/js/object-freeze.html")}}
+ +

語法

+ +
Object.freeze(obj)
+ +

參數

+ +
+
obj
+
要被凍結的物件
+
+ +

回傳值

+ +

被凍結的物件

+ +

描述

+ +

一個被凍結的物件無法被新增或刪除屬性。任何想要改動的嘗試都會失敗, 要不沈默地失敗, 就是丟出一個 {{jsxref("TypeError")}} 例外 (此例外最常出現在 {{jsxref("Strict_mode", "strict mode", "", 1)}})

+ +

資料屬性無法被改變。訪問者方法 - setters 也一樣不能改變資料屬性 (雖然它會給你可以改變資料值的假象)。注意! 如果資料屬性是物件的話,該物件的值是可以被改變的,除非它們也被凍結。一個陣列同樣可以被凍結 (因為它也是一個物件),被凍結後它的元素內容就不能被改變,也不能新增或刪除元素。

+ +

範例

+ +

凍結物件

+ +
var obj = {
+  prop: function() {},
+  foo: 'bar'
+};
+
+// 新的屬性可以被新增,原本的屬性可以被改變或刪除
+obj.foo = 'baz';
+obj.lumpy = 'woof';
+delete obj.prop;
+
+// 回傳的物件跟原本傳入的物件是同一個,所以不需要記住回傳值
+// 也可以凍結一個物件
+var o = Object.freeze(obj);
+
+o === obj; // true
+Object.isFrozen(obj); // === true
+
+// 現在任何改動都會失敗
+obj.foo = 'quux'; // 什麼事也不會發生
+// 屬性無法被新增
+obj.quaxxor = 'the friendly duck';
+
+// 在嚴格模式中,如方才的嘗試都會丟出 TypeError
+function fail(){
+  'use strict';
+  obj.foo = 'sparky'; // 丟出 TypeError
+  delete obj.foo; // 丟出 TypeError
+  delete obj.quaxxor; // 回傳 true 因為屬性 'quaxxor' 從來沒有被新增
+  obj.sparky = 'arf'; // 丟出 TypeError
+}
+
+fail();
+
+// 嘗試透過 Object.defineProperty 來改變屬性的值會丟出 TypeError
+Object.defineProperty(obj, 'ohai', { value: 17 });
+Object.defineProperty(obj, 'foo', { value: 'eit' });
+
+// 一樣不可能改變物件的原型,都會丟出 TypeError
+Object.setPrototypeOf(obj, { x: 20 })
+obj.__proto__ = { x: 20 }
+
+ +

凍結陣列

+ +
let a = [0];
+Object.freeze(a); // 現在這個陣列不能被改動
+
+a[0]=1; // 沈默地失敗
+a.push(2); // 沈默地失敗
+
+// 在嚴格模式底下會丟出 TypeError
+function fail() {
+  "use strict"
+  a[0] = 1;
+  a.push(2);
+}
+
+fail();
+ +

被凍結的物件是不可變 (Immutable) 的。然而,它並不等於常數 (constant)。以下的範例顯示一個被凍結的物件並不是常數 (凍結的動作是「淺」的 - 如果資料屬性也是物件, 不會遞迴地做凍結的動作)。

+ +
obj1 = {
+  internal: {}
+};
+
+Object.freeze(obj1);
+obj1.internal.a = 'aValue';
+
+obj1.internal.a // 'aValue'
+ +

如果要成為一個常數物件,整個物件參考圖 (包含直接指向或間接指向其他物件) 必須都只能指向被凍結的不可變物件。一個物件被稱作不可變是因為它的整個物件狀態 (值或是指向其他物件的參考) 是固定的。注意,string, number 和 boolean 這些原始型別的值是永遠不變的,Function 和 Array 都屬於物件的一種。

+ +

要讓一個物件變成常數物件,就必須遞迴地凍結每個是物件型別的屬性 (稱作深凍結)。只有當你知道物件的參考圖不存在任何循環 的時候才能使用以上遞迴的方式來凍結物件,不然就可能會造成無窮迴圈。一個改善以下範例中 deepFreeze() 來解決無窮迴圈問題的方法是 - 創建一個接受一個路徑參數 (像是陣列) 的內部用函數,用來避免無窮遞迴地呼叫 deepFreeze() - 當發現欲凍結的物件已經出現在之前凍結的物件行列中就不繼續遞迴下去。需要注意的是你可能會不小心凍結一個不應該被凍結的物件,像是 [window]。

+ +
// 用這個函數來進行對物件的深凍結
+function deepFreeze(obj) {
+
+  // 取得物件的所有屬性名稱
+  var propNames = Object.getOwnPropertyNames(obj);
+
+  // 在凍結物件本身之前先凍結物件的所有物件屬性
+  propNames.forEach(function(name) {
+    var prop = obj[name];
+
+    // 凍結 prop 如果它是一個物件
+    if (typeof prop == 'object' && prop !== null)
+      deepFreeze(prop);
+  });
+
+  // 凍結本身 (no-op 如果已經被凍結了)
+  return Object.freeze(obj);
+}
+
+obj2 = {
+  internal: {}
+};
+
+deepFreeze(obj2);
+obj2.internal.a = 'anotherValue';
+obj2.internal.a; // undefined
+ +

備註

+ +

在 ES5 中,如果傳入此方法的參數不是一個物件 (原始型別),{{jsxref("TypeError")}} 就會被丟出。而在 ES2015,一個非物件型態的參數會被當成是一個已經被凍結的物件,所以會被直接回傳?不會造成錯誤。

+ +
> Object.freeze(1)
+TypeError: 1 is not an object // ES5 code
+
+> Object.freeze(1)
+1                             // ES2015 code
+
+ +

與 Object.seal() 的差別

+ +

被 Object.seal() 密封的物件還是可以改變它原有屬性的值。而被 Object.freeze() 凍結的物件則無法改變它原有屬性的值因為他們是不可變的。

+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + +
規格狀態備註
{{SpecName('ES5.1', '#sec-15.2.3.9', 'Object.freeze')}}{{Spec2('ES5.1')}}第一版。實作於 JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Object.freeze")}}

+
+ +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html new file mode 100644 index 0000000000..ff4e4d480f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html @@ -0,0 +1,128 @@ +--- +title: Object.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +tags: + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +--- +
{{JSRef}}
+ +

Object.getPrototypeOf() 回傳指定物件的原型,換句話說,就是取得該物件的 [[Prototype]] 屬性的值).

+ +

表達式

+ +
Object.getPrototypeOf(obj)
+ +

參數

+ +
+
obj
+
欲取得原型的物件。
+
+ +

範例

+ +
var proto = {};
+var obj = Object.create(proto);
+Object.getPrototypeOf(obj) === proto; // true
+
+ +

備註

+ +

如果 obj 參數在 ES5 並不是物件時會拋出 {{jsxref("TypeError")}} 例外,同樣狀況在 ES6 時該參數將會被強制轉換成 {{jsxref("Object")}}。

+ +
Object.getPrototypeOf("foo");
+// TypeError: "foo" is not an object (ES5 code)
+Object.getPrototypeOf("foo");
+// String.prototype                  (ES6 code)
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}Initial definition.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Opera 註

+ +

雖然舊版的 Opera 並不支援 Object.getPrototypeOf(),但是 Opera 從 Opera 10.50 支援非標準的 {{jsxref("Object.proto", "__proto__")}} 屬性。

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html new file mode 100644 index 0000000000..1786387141 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -0,0 +1,184 @@ +--- +title: Object.prototype.hasOwnProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +--- +
{{JSRef}}
+ +

hasOwnProperty() 回傳物件是否有該屬性的布林值。

+ +

表達式

+ +
obj.hasOwnProperty(prop)
+ +

參數

+ +
+
prop
+
屬性名稱。
+
+ +

說明

+ +

每個為 {{jsxref("Object")}} 後代的物件都繼承 hasOwnProperty 方法。這個方法可以被使用來決定物件是否擁有特定的直接屬性;跟 {{jsxref("Operators/in", "in")}} 不一樣,這個方法並未檢查物件的原型鏈。

+ +

範例

+ +

使用 hasOwnProperty 測試屬性是否存在

+ +

這個範例顯示 o 物件是否擁有名為 prop 的屬性:

+ +
o = new Object();
+o.prop = 'exists';
+
+function changeO() {
+  o.newprop = o.prop;
+  delete o.prop;
+}
+
+o.hasOwnProperty('prop');   // 回傳 true
+changeO();
+o.hasOwnProperty('prop');   // 回傳 false
+
+ +

直接與繼承的屬性

+ +

這個範例區分直接屬性和從原型鍊繼承的屬性:

+ +
o = new Object();
+o.prop = 'exists';
+o.hasOwnProperty('prop');             // 回傳 true
+o.hasOwnProperty('toString');         // 回傳 false
+o.hasOwnProperty('hasOwnProperty');   // 回傳 false
+
+ +

遍歷物件的屬性

+ +

這個範例顯示如何不執行繼承的屬性去遍歷物件的屬性。注意 {{jsxref("Statements/for...in", "for...in")}} 已經遍歷了可以被列舉的項目,所以不該基於缺乏不可列舉的屬性(如下)而假設 hasOwnProperty 被嚴格地限制在列舉的項目(如同 {{jsxref("Object.getOwnPropertyNames()")}})。

+ +
var buz = {
+  fog: 'stack'
+};
+
+for (var name in buz) {
+  if (buz.hasOwnProperty(name)) {
+    console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);
+  }
+  else {
+    console.log(name); // toString or something else
+  }
+}
+
+ +

將 hasOwnProperty 作為屬性

+ +

JavaScript 並未保護 hasOwnProperty;因此,如果一個物件擁有一樣的屬性名稱,為了獲得正確的結果需要使用 external hasOwnProperty

+ +
var foo = {
+  hasOwnProperty: function() {
+    return false;
+  },
+  bar: 'Here be dragons'
+};
+
+foo.hasOwnProperty('bar'); // 總是回傳 false
+
+// 使用其他物件的 hasOwnProperty 和 call it with 'this' set to foo
+({}).hasOwnProperty.call(foo, 'bar'); // true
+
+// 從物件的原型使用 hasOwnProperty 也是可行的
+Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
+
+ +

註:在最後一個例子中並未創建任何新的物件。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES6')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..3885c44a15 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,222 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - NeedsTranslation + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

Object 建構式可用於建立物件包裝(object wrapper)。

+ +

語法

+ +
// Object initialiser or literal
+{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
+
+// Called as a constructor
+new Object([value])
+ +

參數

+ +
+
nameValuePair1, nameValuePair2, ... nameValuePairN
+
Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.
+
value
+
任意值。
+
+ +

描述

+ +

The Object constructor creates an object wrapper for the given value. If the value is {{jsxref("null")}} or {{jsxref("undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

+ +

When called in a non-constructor context, Object behaves identically to new Object().

+ +

也可以參考 object initializer / literal syntax.

+ +

Object 建構式屬性

+ +
+
Object.length
+
Has a value of 1.
+
{{jsxref("Object.prototype")}}
+
Allows the addition of properties to all objects of type Object.
+
+ +

Object 建構式方法

+ +
+
{{jsxref("Object.assign()")}}
+
Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object.
+
{{jsxref("Object.create()")}}
+
Creates a new object with the specified prototype object and properties.
+
{{jsxref("Object.defineProperty()")}}
+
Adds the named property described by a given descriptor to an object.
+
{{jsxref("Object.defineProperties()")}}
+
Adds the named properties described by the given descriptors to an object.
+
{{jsxref("Object.entries()")}} {{experimental_inline}}
+
Returns an array of a given object's own enumerable property [key, value] pairs.
+
{{jsxref("Object.freeze()")}}
+
Freezes an object: other code can't delete or change any properties.
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Returns a property descriptor for a named property on an object.
+
{{jsxref("Object.getOwnPropertyDescriptors()")}}
+
Returns an object containing all own property descriptors for an object.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
+
{{jsxref("Object.getOwnPropertySymbols()")}}
+
Returns an array of all symbol properties found directly upon a given object.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Returns the prototype of the specified object.
+
{{jsxref("Object.is()")}}
+
Compares if two values are distinguishable (ie. the same)
+
{{jsxref("Object.isExtensible()")}}
+
Determines if extending of an object is allowed.
+
{{jsxref("Object.isFrozen()")}}
+
Determines if an object was frozen.
+
{{jsxref("Object.isSealed()")}}
+
Determines if an object is sealed.
+
{{jsxref("Object.keys()")}}
+
Returns an array containing the names of all of the given object's own enumerable properties.
+
{{jsxref("Object.preventExtensions()")}}
+
Prevents any extensions of an object.
+
{{jsxref("Object.seal()")}}
+
Prevents other code from deleting properties of an object.
+
{{jsxref("Object.setPrototypeOf()")}}
+
Sets the prototype (i.e., the internal [[Prototype]] property)
+
{{jsxref("Object.values()")}} {{experimental_inline}}
+
Returns an array of a given object's own enumerable values.
+
+ +

Object 物件實體與 Object 原型物件

+ +

All objects in JavaScript are descended from Object; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString() methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

+ +

屬性

+ +
{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', '屬性') }}
+ +

方法

+ +
{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', '方法') }}
+ +

範例

+ +

Using Object given undefined and null types

+ +

下面例子儲存一個空物件至變數o

+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

Using Object to create Boolean objects

+ +

下面例子儲存 {{jsxref("Boolean")}} 物件在 o:

+ +
// equivalent to o = new Boolean(true);
+var o = new Object(true);
+
+ +
// equivalent to o = new Boolean(false);
+var o = new Object(Boolean());
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}}Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html new file mode 100644 index 0000000000..958b9a3a47 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html @@ -0,0 +1,208 @@ +--- +title: Object.keys() +slug: Web/JavaScript/Reference/Global_Objects/Object/keys +tags: + - ECMAScript 5 + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys +--- +
{{JSRef}}
+ +

Object.keys() 方法會回傳一個由指定物件所有可列舉之屬性組成的陣列,該陣列中的的排列順序與使用 {{jsxref("Statements/for...in", "for...in")}} 進行迭代的順序相同(兩者的差異在於 for-in 迴圈還會迭代出物件自其原型鏈所繼承來的可列舉屬性)。

+ +

語法

+ +
Object.keys(obj)
+ +

參數

+ +
+
obj
+
物件,用以回傳其可列舉屬性。
+
+ +

回傳值

+ +

回傳一個包含給定物件內所有可列舉屬性的字串陣列。

+ +

描述

+ +

Object.keys() 回傳一個陣列,陣列中的各元素為直屬於 obj ,對應可列舉屬性名的字串。回傳結果的排序,與手動對物件屬性作迴圈迭代的結果排序相同。

+ +

範例

+ +
var arr = ['a', 'b', 'c'];
+console.log(Object.keys(arr)); // console: ['0', '1', '2']
+
+// 類似陣列的物件
+var obj = { 0: 'a', 1: 'b', 2: 'c' };
+console.log(Object.keys(obj)); // console: ['0', '1', '2']
+
+// 擁有隨機 key 排序,類似陣列的物件
+var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
+console.log(Object.keys(an_obj)); // console: ['2', '7', '100']
+
+// getFoo 不是可列舉的屬性
+var my_obj = Object.create({}, {
+  getFoo: {
+    value: function() { return this.foo; }
+  }
+});
+my_obj.foo = 1;
+
+console.log(Object.keys(my_obj)); // console: ['foo']
+
+ +

如果想取得物件的所有屬性,包括非可列舉的屬性,請參閱 {{jsxref("Object.getOwnPropertyNames()")}}.

+ +

備註

+ +

在 ES5 中,如果這個方法的參數不是一個標準物件(例如原始型別),將會產生 {{jsxref("TypeError")}}錯誤。而在 ES2015,非物件的參數將會強制轉換成物件。

+ +
Object.keys("foo");
+// TypeError: "foo" is not an object (ES5 code)
+
+Object.keys("foo");
+// ["0", "1", "2"]                   (ES2015 code)
+
+ +

Polyfill

+ +

如需在原生不支援、較舊的環境中增加 Object.keys 的相容性,請複製以下片段:

+ +
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
+if (!Object.keys) {
+  Object.keys = (function() {
+    'use strict';
+    var hasOwnProperty = Object.prototype.hasOwnProperty,
+        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
+        dontEnums = [
+          'toString',
+          'toLocaleString',
+          'valueOf',
+          'hasOwnProperty',
+          'isPrototypeOf',
+          'propertyIsEnumerable',
+          'constructor'
+        ],
+        dontEnumsLength = dontEnums.length;
+
+    return function(obj) {
+      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
+        throw new TypeError('Object.keys called on non-object');
+      }
+
+      var result = [], prop, i;
+
+      for (prop in obj) {
+        if (hasOwnProperty.call(obj, prop)) {
+          result.push(prop);
+        }
+      }
+
+      if (hasDontEnumBug) {
+        for (i = 0; i < dontEnumsLength; i++) {
+          if (hasOwnProperty.call(obj, dontEnums[i])) {
+            result.push(dontEnums[i]);
+          }
+        }
+      }
+      return result;
+    };
+  }());
+}
+
+ +

請注意以上的代碼片段在 IE7 中( IE8 也有可能 ),從不同的 window 傳入物件將包含非可列舉的 key 。

+ +

較精簡的瀏覽器 Polyfill,請參閱 Javascript - Object.keys Browser Compatibility.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES2015', '#sec-object.keys', 'Object.keys')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-object.keys', 'Object.keys')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html new file mode 100644 index 0000000000..bc046cf87b --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html @@ -0,0 +1,179 @@ +--- +title: Object.preventExtensions() +slug: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +translation_of: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +--- +
{{JSRef}}
+ +

Object.preventExtensions() 用來避免物件被新增新的屬性。

+ +

語法

+ +
Object.preventExtensions(obj)
+ +

參數

+ +
+
obj
+
要被用作無法擴充的物件。
+
+ +

描述

+ +

物件如果可以被增加新的屬性,我們稱它可以被擴充(extensible)。Object.preventExtensions() 標註物件使它無法被擴充,所以在它被標註為無法擴充當下,它將無法再增加新的屬性。不過注意一點,在一般狀況下,被標註為無法擴充的物件,其屬性仍可被刪除(deleted)。嘗試去增加屬性將會導致失敗,可能會沒有結果產生,或是傳回一個 {{jsxref("TypeError")}} (最常見,但並不是一定,當在{{jsxref("Functions_and_function_scope/Strict_mode", "strict mode", "", 1)}})。

+ +

Object.preventExtensions() 只有避免物件被增加屬性,屬性仍可以被增加至 object prototype 。不過,呼叫 Object.preventExtensions() 使用在物件上,就可以使其 {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} 屬性無法被擴充。

+ +

如果能把可擴充物件,轉成無法擴充物件,在 ECMAScript 5 規範中,它並沒有任何方法轉回來。

+ +

範例

+ +
// Object.preventExtensions 傳回一個被無法擴充的物件
+var obj = {};
+var obj2 = Object.preventExtensions(obj);
+obj === obj2; // true
+
+// 預設下,物件可以被擴充
+var empty = {};
+Object.isExtensible(empty); // === true
+
+// ...但是以下情況之後,無法再被變更。
+Object.preventExtensions(empty);
+Object.isExtensible(empty); // === false
+
+// Object.defineProperty throws 當為無法擴充的物件增加屬性
+var nonExtensible = { removable: true };
+Object.preventExtensions(nonExtensible);
+Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // throws a TypeError
+
+// 在 strict mode 中,嘗試去新增屬性給無法擴充物件,將 throws 出一個 TypeError。
+function fail() {
+  'use strict';
+  nonExtensible.newProperty = 'FAIL'; // throws a TypeError
+}
+fail();
+
+// EXTENSION (only works in engines supporting __proto__
+// (which is deprecated. Use Object.getPrototypeOf instead)):
+// A non-extensible object's prototype is immutable.
+var fixed = Object.preventExtensions({});
+fixed.__proto__ = { oh: 'hai' }; // throws a TypeError
+
+ +

筆記

+ +

在ES5中,如果給祝個方法的參數為非物件,它將造成一個 {{jsxref("TypeError")}} 。不過在 ES6 中,非物件參數會被正常處理。另外,如果它原本就是個無法擴充物件,就只是回傳本身。

+ +
Object.preventExtensions(1);
+// TypeError: 1 is not an object (ES5 code)
+
+Object.preventExtensions(1);
+// 1                             (ES6 code)
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容度

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("6")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
ES6 behavior for non-object argument{{CompatChrome("44")}}{{CompatGeckoDesktop("35.0")}}{{CompatIE("11")}}{{CompatOpera("31")}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ES6 behavior for non-object argument{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("35.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

閱讀更多

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html new file mode 100644 index 0000000000..5ba5c8f615 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html @@ -0,0 +1,137 @@ +--- +title: Object.prototype.__proto__ +slug: Web/JavaScript/Reference/Global_Objects/Object/proto +translation_of: Web/JavaScript/Reference/Global_Objects/Object/proto +--- +
+

Warning: 基於現代Javascript引擎最佳化物件屬性存取的方法,改變一個物件的 [[Prototype]] 在任何瀏覽器或是Javascript引擎都是非常慢的操作?。改變繼承屬性對效能的影響微妙且深遠,不僅僅只是影響執行 obj.__proto__ = ... 的時間,而是會影響到所有有存取到被改變 [[Prototype]] 的物件的程式碼的執行時間。如果你在乎效能的話就應該避免改變一個物件的 [[Prototype]] 。反之,請用 {{jsxref("Object.create()")}} 來產生一個擁有 [[Prototype]] 的物件。

+
+ +
+

Warning: 雖然 Object.prototype.__proto__ 在今日已經被絕大部分的瀏覽器所支援,其存在與確切的行為只有在 ECMAScript 2015 規範才被標準化成一個歷史功能來確保相容性。為了更好的支援,建議使用{{jsxref("Object.getPrototypeOf()")}}。

+
+ +
{{JSRef}}
+ +

The __proto__ property of {{jsxref("Object.prototype")}} is an accessor property (a getter function and a setter function) that exposes the internal [[Prototype]] (either an object or {{jsxref("Global_Objects/null", "null")}}) of the object through which it is accessed.

+ +

The use of __proto__ is controversial, and has been discouraged. It was never originally included in the EcmaScript language spec, but modern browsers decided to implement it anyway. Only recently, the __proto__ property has been standardized in the ECMAScript 2015 language specification for web browsers to ensure compatibility, so will be supported into the future. It is deprecated in favor of {{jsxref("Object.getPrototypeOf")}}/{{jsxref("Reflect.getPrototypeOf")}} and {{jsxref("Object.setPrototypeOf")}}/{{jsxref("Reflect.setPrototypeOf")}} (though still, setting the [[Prototype]] of an object is a slow operation that should be avoided if performance is a concern).

+ +

The __proto__ property can also be used in an object literal definition to set the object [[Prototype]] on creation, as an alternative to {{jsxref("Object.create()")}}. See: object initializer / literal syntax.

+ +

Syntax

+ +
var Circle = function () {};
+var shape = {};
+var circle = new Circle();
+
+// Set the object prototype.
+// DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code.
+shape.__proto__ = circle;
+
+// Get the object prototype
+console.log(shape.__proto__ === circle); // true
+
+ +
var shape = function () {};
+var p = {
+    a: function () {
+        console.log('aaa');
+    }
+};
+shape.prototype.__proto__ = p;
+
+var circle = new shape();
+circle.a(); // aaa
+console.log(shape.prototype === circle.__proto__); // true
+
+// or
+var shape = function () {};
+var p = {
+    a: function () {
+        console.log('a');
+    }
+};
+
+var circle = new shape();
+circle.__proto__ = p;
+circle.a(); // a
+console.log(shape.prototype === circle.__proto__); // false
+
+// or
+function test() {};
+test.prototype.myname = function () {
+    console.log('myname');
+};
+
+var a = new test();
+console.log(a.__proto__ === test.prototype); // true
+a.myname(); // myname
+
+
+// or
+var fn = function () {};
+fn.prototype.myname = function () {
+    console.log('myname');
+};
+
+var obj = {
+    __proto__: fn.prototype
+};
+
+obj.myname(); // myname
+
+ +

Note: that is two underscores, followed by the five characters "proto", followed by two more underscores.

+ +

Description

+ +

The __proto__ getter function exposes the value of the internal [[Prototype]] of an object. For objects created using an object literal, this value is {{jsxref("Object.prototype")}}. For objects created using array literals, this value is {{jsxref("Array.prototype")}}. For functions, this value is {{jsxref("Function.prototype")}}. For objects created using new fun, where fun is one of the built-in constructor functions provided by JavaScript ({{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("String")}}, and so on — including new constructors added as JavaScript evolves), this value is always fun.prototype. For objects created using new fun, where fun is a function defined in a script, this value is the value of fun.prototype. (That is, if the constructor didn't return an other object explicitly, or the fun.prototype has been reassigned since the instance was created).

+ +

The __proto__ setter allows the [[Prototype]] of an object to be mutated. The object must be extensible according to {{jsxref("Object.isExtensible()")}}: if it is not, a {{jsxref("Global_Objects/TypeError", "TypeError")}} is thrown. The value provided must be an object or {{jsxref("Global_Objects/null", "null")}}. Providing any other value will do nothing.

+ +

To understand how prototypes are used for inheritance, see guide article Inheritance and the prototype chain.

+ +

The __proto__ property is a simple accessor property on {{jsxref("Object.prototype")}} consisting of a getter and setter function. A property access for __proto__ that eventually consults {{jsxref("Object.prototype")}} will find this property, but an access that does not consult {{jsxref("Object.prototype")}} will not find it. If some other __proto__ property is found before {{jsxref("Object.prototype")}} is consulted, that property will hide the one found on {{jsxref("Object.prototype")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-additional-properties-of-the-object.prototype-object', 'Object.prototype.__proto__')}}{{Spec2('ES2015')}}Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).
{{SpecName('ESDraft', '#sec-additional-properties-of-the-object.prototype-object', 'Object.prototype.__proto__')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object.proto")}}

+
+ +

Compatibility notes

+ +

While the ECMAScript 2015 specification dictates that support for __proto__ is required only for web browsers (although being normative), other environments may support it as well for legacy usage.

+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html new file mode 100644 index 0000000000..21c2a53985 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html @@ -0,0 +1,218 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +tags: + - JavaScript + - Object + - 待翻譯 +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

Object.prototype 代表 {{jsxref("Object")}} 的原型物件。

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

描述

+ +

All objects in JavaScript are descended from {{jsxref("Object")}}; all objects inherit methods and properties from Object.prototype, although they may be overridden (except an Object with a null prototype, i.e. Object.create(null)). For example, other constructors' prototypes override the constructor property and provide their own {{jsxref("Object.prototype.toString()", "toString()")}} methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

+ +

屬性

+ +
+
{{jsxref("Object.prototype.constructor")}}
+
Specifies the function that creates an object's prototype.
+
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
+
Points to the object which was used as prototype when the object was instantiated.
+
{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}
+
Allows a function to be defined that will be executed when an undefined object member is called as a method.
+
{{jsxref("Object.prototype.__count__")}} {{obsolete_inline}}
+
Used to return the number of enumerable properties directly on a user-defined object, but has been removed.
+
{{jsxref("Object.prototype.__parent__")}} {{obsolete_inline}}
+
Used to point to an object's context, but has been removed.
+
+ +

方法

+ +
+
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associates a function with a property that, when accessed, executes that function and returns its return value.
+
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associates a function with a property that, when set, executes that function which modifies the property.
+
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns the function associated with the specified property by the {{jsxref("Object.defineGetter", "__defineGetter__")}} method.
+
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns the function associated with the specified property by the {{jsxref("Object.defineSetter", "__defineSetter__")}} method.
+
{{jsxref("Object.prototype.hasOwnProperty()")}}
+
Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
+
{{jsxref("Object.prototype.isPrototypeOf()")}}
+
Returns a boolean indication whether the specified object is in the prototype chain of the object this method is called upon.
+
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
+
Returns a boolean indicating if the internal ECMAScript DontEnum attribute is set.
+
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
+
Returns string containing the source of an object literal representing the object that this method is called upon; you can use this value to create a new object.
+
{{jsxref("Object.prototype.toLocaleString()")}}
+
Calls {{jsxref("Object.toString", "toString()")}}.
+
{{jsxref("Object.prototype.toString()")}}
+
Returns a string representation of the object.
+
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
+
Removes a watchpoint from a property of the object.
+
{{jsxref("Object.prototype.valueOf()")}}
+
Returns the primitive value of the specified object.
+
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
+
Adds a watchpoint to a property of the object.
+
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
+
Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.
+
+ +

範例

+ +

因為 JavaScript 並沒有子類別的物件,所以原型是個很有用的解決辦法, 使某些函數作為物件的基本類別物件。例如:

+ +
var Person = function() {
+  this.canTalk = true;
+};
+
+Person.prototype.greet = function() {
+  if (this.canTalk) {
+    console.log('Hi, I am ' + this.name);
+  }
+};
+
+var Employee = function(name, title) {
+  Person.call(this);
+  this.name = name;
+  this.title = title;
+};
+
+Employee.prototype = Object.create(Person.prototype);
+Employee.prototype.constructor = Employee;
+
+Employee.prototype.greet = function() {
+  if (this.canTalk) {
+    console.log('Hi, I am ' + this.name + ', the ' + this.title);
+  }
+};
+
+var Customer = function(name) {
+  Person.call(this);
+  this.name = name;
+};
+
+Customer.prototype = Object.create(Person.prototype);
+Customer.prototype.constructor = Customer;
+
+var Mime = function(name) {
+  Person.call(this);
+  this.name = name;
+  this.canTalk = false;
+};
+
+Mime.prototype = Object.create(Person.prototype);
+Mime.prototype.constructor = Mime;
+
+var bob = new Employee('Bob', 'Builder');
+var joe = new Customer('Joe');
+var rg = new Employee('Red Green', 'Handyman');
+var mike = new Customer('Mike');
+var mime = new Mime('Mime');
+
+bob.greet();
+// Hi, I am Bob, the Builder
+
+joe.greet();
+// Hi, I am Joe
+
+rg.greet();
+// Hi, I am Red Green, the Handyman
+
+mike.greet();
+// Hi, I am Mike
+
+mime.greet();
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html new file mode 100644 index 0000000000..9dc8afa27f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html @@ -0,0 +1,191 @@ +--- +title: Object.prototype.watch() +slug: Web/JavaScript/Reference/Global_Objects/Object/watch +translation_of: Archive/Web/JavaScript/Object.watch +--- +
{{JSRef}}
+ +
+

Warning: Generally you should avoid using watch() and {{jsxref("Object.prototype.unwatch", "unwatch()")}} when possible. These two methods are implemented only in Gecko, and they're intended primarily for debugging use. In addition, using watchpoints has a serious negative impact on performance, which is especially true when used on global objects, such as window. You can usually use setters and getters or proxies instead. See {{anch("Browser compatibility")}} for details. Also, do not confuse {{jsxref("Object.prototype.watch", "Object.watch")}} with {{jsxref("Object.prototype.observe", "Object.observe")}}.

+
+ +

The watch() method watches for a property to be assigned a value and runs a function when that occurs.

+ +

語法

+ +
obj.watch(prop, handler)
+ +

參數

+ +
+
prop
+
所需要監聽其值是否改變的物件屬性
+
handler
+
當監聽的變數其數值變換時所執行的function
+
+ +

回傳值

+ +

{{jsxref("undefined")}}.

+ +

Description

+ +

Watches for assignment to a property named prop in this object, 呼叫 handler(prop, oldval, newval) whenever prop is set and storing the return value in that property. A watchpoint can filter (or nullify) the value assignment, by returning a modified newval (or by returning oldval).

+ +

當你刪掉所監聽的物件屬性,並不會結束針對該物件屬性的監聽。當你重新產生該屬性時,監聽依舊維持作用。

+ +

要停止該次監聽, 須使用 {{jsxref("Object.unwatch", "unwatch()")}} 函式. By default, the watch method is inherited by every object descended from {{jsxref("Object")}}.

+ +

The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Venkman.

+ +

In Firefox, handler is only called from assignments in script, not from native code. For example, window.watch('location', myHandler) will not call myHandler if the user clicks a link to an anchor within the current document. However, window.location += '#myAnchor' will call myHandler.

+ +
+

Note: Calling watch() on an object for a specific property overrides any previous handler attached for that property.

+
+ +

範例

+ +

使用watch 和 unwatch

+ +
var o = { p: 1 };
+
+o.watch('p', function (id, oldval, newval) {
+  console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval);
+  return newval;
+});
+
+o.p = 2;
+o.p = 3;
+delete o.p;
+o.p = 4;
+
+o.unwatch('p');
+o.p = 5;
+
+ +

上述程式執行結果:

+ +
o.p changed from 1 to 2
+o.p changed from 2 to 3
+o.p changed from undefined to 4
+
+ +

使用 watch 驗證物件的屬性

+ +

You can use watch to test any assignment to an object's properties. This example ensures that every Person always has a valid name and an age between 0 and 200.

+ +
Person = function(name, age) {
+  this.watch('age', Person.prototype._isValidAssignment);
+  this.watch('name', Person.prototype._isValidAssignment);
+  this.name = name;
+  this.age = age;
+};
+
+Person.prototype.toString = function() {
+  return this.name + ', ' + this.age;
+};
+
+Person.prototype._isValidAssignment = function(id, oldval, newval) {
+  if (id === 'name' && (!newval || newval.length > 30)) {
+    throw new RangeError('invalid name for ' + this);
+  }
+  if (id === 'age'  && (newval < 0 || newval > 200)) {
+    throw new RangeError('invalid age for ' + this);
+  }
+  return newval;
+}
+
+will = new Person('Will', 29);
+console.log(will);   // Will, 29
+
+try {
+  will.name = '';
+} catch (e) {
+  console.log(e);
+}
+
+try {
+  will.age = -4;
+} catch (e) {
+  console.log(e);
+}
+
+ +

上述程式執行結果:

+ +
Will, 29
+RangeError: invalid name for Will, 29
+RangeError: invalid age for Will, 29
+
+ +

規格

+ +

Not part of any specifications. Implemented in JavaScript 1.2.

+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Compatibility notes

+ + + +

參閱

+ + -- cgit v1.2.3-54-g00ecf