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 | 259 +++++++++++ .../object/defineproperties/index.html | 228 ++++++++++ .../object/defineproperty/index.html | 483 +++++++++++++++++++++ .../object/getownpropertynames/index.html | 156 +++++++ .../reference/global_objects/object/index.html | 213 +++++++++ .../global_objects/object/observe/index.html | 193 ++++++++ .../global_objects/object/tostring/index.html | 128 ++++++ .../global_objects/object/valueof/index.html | 108 +++++ 8 files changed, 1768 insertions(+) create mode 100644 files/vi/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html create mode 100644 files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html create mode 100644 files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html create mode 100644 files/vi/web/javascript/reference/global_objects/object/index.html create mode 100644 files/vi/web/javascript/reference/global_objects/object/observe/index.html create mode 100644 files/vi/web/javascript/reference/global_objects/object/tostring/index.html create mode 100644 files/vi/web/javascript/reference/global_objects/object/valueof/index.html (limited to 'files/vi/web/javascript/reference/global_objects/object') diff --git a/files/vi/web/javascript/reference/global_objects/object/assign/index.html b/files/vi/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..2f5b00f1ec --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,259 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +tags: + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +
{{JSRef}}
+ +

Object.assign() được sử dụng để sao chép các giá trị của tất cả thuộc tính có thể liệt kê từ một hoặc nhiều đối tượng nguồn đến một đối tượng đích. Nó sẽ  trả về đối tượng đích đó.

+ +

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

+ +

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

+ +

Cú pháp

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

Các tham số

+ +
+
target
+
Đối tượng đích
+
sources
+
Các đối tượng nguồn
+
+ +

Giá trị trả về

+ +

(Các) Đối tượng đích

+ +

Mô tả

+ +

Các thuộc tính trong đối tượng đích sẽ bị ghi lại bởi các thuộc tính trong đối tượng nguồn nếu chúng có cùng key. Tương tự, các thuộc tính nguồn sau sẽ ghi đè lên những thuộc tính nguồn trước. 

+ +

Phương thức Object.assign() chỉ sao chép những giá trị liệt kê được và và các thuộc tính của bản thân nó đến đối tượng đích. Nó sử dụng  [[Get]] trên nguồn và [[Set]] trên đích, vì vậy nó sẽ gọi các hàm getter và setter.  Vì lý do đó nó chỉ định thuộc tính so với việc chỉ sao chép hoặc xác đinh các thuộc tính mới. Điều này có thể khiến nó không phù hợp khi gộp các thuộc tính mới vào một nguyên mẫu (prototype) nếu các nguồn gộp chứa các getter. Để sao chép các thuộc tính xác định, bao gồm cả khả năng đếm được vào trong các nguyên mẫu thì nên sử dụng {{jsxref("Object.getOwnPropertyDescriptor()")}} và {{jsxref("Object.defineProperty()")}} để thay thế.

+ +

Các thuộc tính {{jsxref("String")}} và {{jsxref("Symbol")}} đều được sao chép.

+ +

Trong trường hợp có một lỗi, như việc một thuộc tính không được phép ghi đè, một  {{jsxref("TypeError")}}  sẽ sinh ra, và đối tượng đích có thể được thay đổi nếu có bất kỳ thuộc tính nào đã được thêm vào trước khi lỗi được sinh ra.

+ +

Chú ý rằng Object.assign() không ném ra một {{jsxref("null")}} hoặc {{jsxref("undefined")}}.

+ +

Ví dụ

+ +

Sao chép một object

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

Cảnh báo về Deep Clone

+ +

Với deep cloning, chúng ta cần sử dụng những lựa chọn khác khác bởi vì Object.assign() sao chép các giá trị thuộc tính. Nếu giá trị nguồn là tham chiếu đến một object,  nó chỉ sao chép gía trị tham chiếu đó. 

+ +
function test() {
+  'use strict';
+
+  let a = { b: {c: 4} , d: { e: {f: 1} } };
+  let g = Object.assign({}, a);
+  let h = JSON.parse(JSON.stringify(a));
+  console.log(JSON.stringify(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(JSON.stringify(g)); // { b: { c: 4 }, d: { e: 32 } }
+  console.log(JSON.stringify(a)); // { b: { c: 4 }, d: { e: 32 } }
+  console.log(JSON.stringify(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(JSON.stringify(g)); // { b: { c: 4 }, d: { e: 32 } }
+  console.log(JSON.stringify(a)); // { b: { c: 4 }, d: { e: 32 } }
+  console.log(JSON.stringify(h)); // { b: { c: 4 }, d: { e: 54 } }
+}
+
+test();
+ +

Gộp các object

+ +
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 }, object đích tự nó bị thay đổi.
+ +

Gộp các đối tượng với cùng giá trị

+ +
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ác giá trị được ghi đè bởi các đối tượng khác mà chúng có chung các thuộc tính sau đó theo thứ tự các tham số.

+ +

Sao chép thuộc tính symbol-typed

+ +
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 trên Firefox)
+Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
+
+ +

Các thuộc tính trên chuỗi nguyên mẫu và các thuộc tính không có khả năng đếm được thì không thể sao chép. 

+ +
var obj = Object.create({ foo: 1 }, { // foo ở trên mắt xích prototype của obj.
+  bar: {
+    value: 2  // bar chứa thuộc tính không liệt kê được.
+  },
+  baz: {
+    value: 3,
+    enumerable: true  // baz chứa thuộc tính liệt kê được.
+  }
+});
+
+var copy = Object.assign({}, obj);
+console.log(copy); // { baz: 3 }
+
+ +

Các giá trị nguyên thủy sẽ được gói thành các đối tượng.

+ +
var v1 = 'abc';
+var v2 = true;
+var v3 = 10;
+var v4 = Symbol('foo');
+
+var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
+// Sự nguyên bản sẽ bị gói lại, null và undefined sẽ bị bỏ qua.
+// Ghi chú,chỉ có string wrapper mới có thuộc tính liệt kê được.
+console.log(obj); // { "0": "a", "1": "b", "2": "c" }
+
+ +

Các ngoại lệ sẽ làm gián đoạn quá trình sao chép.

+ +
var target = Object.defineProperty({}, 'foo', {
+  value: 1,
+  writable: false
+}); // target.foo chỉ read-only
+
+Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
+// TypeError: "foo" là read-only
+// Trường hợp ngoại lệ được tạo ra khi gán target.foo
+
+console.log(target.bar);  // 2, nguồn thứ nhất được sao chép thành công
+console.log(target.foo2); // 3, đặc tính thứ nhất của nguồn thứ 2 được chép thành công.
+console.log(target.foo);  // 1, ngoại lệ được ném ra
+console.log(target.foo3); // undefined, phương thức gán đã hoàn tất, foo3 sẽ không bị sao chép
+console.log(target.baz);  // undefined, nguồn thứ ba cũng không bị sao chép
+
+ +

Sao chép các trình truy cập (accessor)

+ +
var obj = {
+  foo: 1,
+  get bar() {
+    return 2;
+  }
+};
+
+var copy = Object.assign({}, obj);
+console.log(copy);
+// { foo: 1, bar: 2 }, giá trị của copy.bar là giá trị return của getter của obj.bar.
+
+// Đây là function gán sao chép toàn bộ các mô tả.
+function completeAssign(target, ...sources) {
+  sources.forEach(source => {
+    let descriptors = Object.keys(source).reduce((descriptors, key) => {
+      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
+      return descriptors;
+    }, {});
+    // Mặc định thì Object.assign sao chép cả Symbol thống kê được luôn
+    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")}}  không hỗ trợ các thuộc tính symbol, kể từ ES5 thì cũng không còn symbol nữa:

+ +
if (typeof Object.assign != 'function') {
+  Object.assign = function(target, varArgs) { // .length của function là 2
+    'use strict';
+    if (target == null) { // TypeError nếu undefined hoặc 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) { // Bỏ qua nếu undefined hoặc 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;
+  };
+}
+
+ +

Đặc tính kỹ thuật

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

Tương thích trình duyệt

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

Xem thêm

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

Phương thức Object.defineProperties() định nghĩa hoặc thay đổi tức thì các thuộc tính của một đối tượng, sau đó trả lại đối tượng đó.

+ +

Cú pháp

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

Các tham số

+ +
+
obj
+
Đối tượng được định nghĩa hoặc thay đổi các thuộc tính.
+
props
+
Đối tượng mà các thuộc tính có thể liệt kê (enumerable) của riêng nó sẽ cấu thành các bộ mô tả (descriptor) cho các thuộc tính được định nghĩa hoặc sửa đổi. Các bộ mô tả thuộc tính (property descriptors) có trong các đối tượng bao gồm hai loại chính: các bộ mô tả dữ liệu (data descriptors) và các bộ mô tả truy cập (accessor descriptors) (xem {{jsxref("Object.defineProperty()")}} để biết thêm chi tiết). Các bộ mô tả bao gồm các khóa sau:
+
+
+
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.
+ Defaults to false.
+
enumerable
+
true if and only if this property shows up during enumeration of the properties on the corresponding object.
+ Defaults to false.
+
+ +
+
value
+
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
+ Defaults to {{jsxref("undefined")}}.
+
writable
+
true if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.
+ Defaults to 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.
+ Defaults to {{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.
+ Defaults to {{jsxref("undefined")}}.
+
+
+
+ +

Giá trị trả về

+ +

Đối tượng được truyền khi gọi phương thức.

+ +

Mô tả

+ +

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

+ +

Ví dụ

+ +
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;
+}
+
+ +

Đặc tả

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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')}} 
+ +

Tương thích trình duyệt

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

Tham khảo

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

Phương thức Object.defineProperty() định nghĩa ngay một thuộc tính mới trên một đối tượng, hoặc thay đổi một thuộc tính đã có trên một đối tượng, và trả về đối tượng đó.

+ +
+

Lưu ý: Bạn có thể gọi phương thức ngay trên  {{jsxref("Object")}} hơn là trên một thể hiện của kiểu Object.

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

Cú pháp

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

Các tham số

+ +
+
obj
+
Object cần định nghĩa thuộc tính.
+
prop
+
Tên của thuộc tính sẽ định nghĩa hoặc sửa đổi.
+
descriptor
+
Mô tả cho thuộc tính được định nghĩa hoặc sửa đổi.
+
+ +

Giá trị trả về

+ +

Object đã được truyền vào hàm.

+ +

Mô tả

+ +

This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration ({{jsxref("Statements/for...in", "for...in")}} loop or {{jsxref("Object.keys")}} method), whose values may be changed, and which may be {{jsxref("Operators/delete", "deleted", "", 1)}}. This method allows these extra details to be changed from their defaults. By default, values added using Object.defineProperty() are immutable.

+ +

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An 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.

+ +

Both data and accessor descriptors are objects. They share the following optional 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.
+ Defaults to false.
+
enumerable
+
true if and only if this property shows up during enumeration of the properties on the corresponding object.
+ Defaults to false.
+
+ +

A data descriptor also has the following optional keys:

+ +
+
value
+
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
+ Defaults to {{jsxref("undefined")}}.
+
writable
+
true if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.
+ Defaults to false.
+
+ +

An accessor descriptor also has the following optional keys:

+ +
+
get
+
A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. When the property is accessed, this function is called without arguments and with this set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property.
+ Defaults to {{jsxref("undefined")}}.
+
set
+
A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. When the property is assigned to, this function is called with one argument (the value being assigned to the property) and with this set to the object through which the property is assigned.
+ Defaults to {{jsxref("undefined")}}.
+
+ +

If a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. If a descriptor has both value or writable and get or set keys, an exception is thrown.

+ +

Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze the {{jsxref("Object.prototype")}} upfront, specify all options explicitly, or point to {{jsxref("null")}} with {{jsxref("Object.create", "Object.create(null)")}}.

+ +
// using __proto__
+var obj = {};
+var descriptor = Object.create(null); // no inherited properties
+// not enumerable, not configurable, not writable as defaults
+descriptor.value = 'static';
+Object.defineProperty(obj, 'key', descriptor);
+
+// 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);
+
+ +

Ví dụ

+ +

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

+ +

Creating a property

+ +

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 inputted.

+ +
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', {
+  // Using shorthand method names (ES2015 feature).
+  // This is equivalent to:
+  // get: function() { return bValue; },
+  // set: function(newValue) { bValue = newValue; },
+  get() { return bValue; },
+  set(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() { return 0xdeadbeef; }
+});
+// throws a TypeError: value appears
+// only in data descriptors,
+// get appears only in accessor descriptors
+
+ +

Modifying a property

+ +

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false the property is said to be “non-configurable”. It is not possible to change any attribute of a non-configurable accessor property. For data properties, it is possible to modify the value if the property is writable, and it is possible to change writable attribute from true to false. It is not possible to switch between data and accessor property types when the property is non-configurable.

+ +

A {{jsxref("TypeError")}} is thrown when attempts are made to change non-configurable property attributes (except value and writable, if permitted) unless the current and new values are the same.

+ +

Writable attribute

+ +

When the writable property attribute is set to false, the property is said to be “non-writable”. It cannot be reassigned.

+ +
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.
+
+// strict mode
+(function() {
+  'use strict';
+  var o = {};
+  Object.defineProperty(o, 'b', {
+    value: 2,
+    writable: false
+  });
+  o.b = 3; // throws TypeError: "b" is read-only
+  return o.b; // returns 2 without the line above
+}());
+
+ +

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

+ +

Enumerable 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
+
+ +

Configurable attribute

+ +

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

+ +
var o = {};
+Object.defineProperty(o, 'a', {
+  get() { 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() {}
+}); // throws a TypeError (set was undefined previously)
+Object.defineProperty(o, 'a', {
+  get() { 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.

+ +

Adding properties and default values

+ +

It is 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

+ +

The 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() {
+      console.log('get!');
+      return temperature;
+    },
+    set(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 }]
+
+ +

In this example, a getter always returns the same value.

+ +
var pattern = {
+    get() {
+        return 'I always return this string, ' +
+               'whatever you have assigned';
+    },
+    set() {
+        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
+
+ +

Inheritance of properties

+ +

If an accessor property is inherited, its get and set methods will be called when the property is accessed and modified on descendant objects. If these methods use a variable to store the value, this value will be shared by all objects.

+ +
function myclass() {
+}
+
+var value;
+Object.defineProperty(myclass.prototype, "x", {
+  get() {
+    return value;
+  },
+  set(x) {
+    value = x;
+  }
+});
+
+var a = new myclass();
+var b = new myclass();
+a.x = 1;
+console.log(b.x); // 1
+
+ +

This can be fixed by storing the value in another property. In get and set methods, this points to the object which is used to access or modify the property.

+ +
function myclass() {
+}
+
+Object.defineProperty(myclass.prototype, "x", {
+  get() {
+    return this.stored_x;
+  },
+  set(x) {
+    this.stored_x = x;
+  }
+});
+
+var a = new myclass();
+var b = new myclass();
+a.x = 1;
+console.log(b.x); // undefined
+
+ +

Unlike accessor properties, value properties are always set on the object itself, not on a prototype. However, if a non-writable value property is inherited, it still prevents from modifying the property on the object.

+ +
function myclass() {
+}
+
+myclass.prototype.x = 1;
+Object.defineProperty(myclass.prototype, "y", {
+  writable: false,
+  value: 1
+});
+
+var a = new myclass();
+a.x = 2;
+console.log(a.x); // 2
+console.log(myclass.prototype.x); // 1
+a.y = 2; // Ignored, throws in strict mode
+console.log(a.y); // 1
+console.log(myclass.prototype.y); // 1
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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')}} 
+ +

Browser compatibility

+ +
+ + +

{{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:

+ + + +

See also

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

The Object.getOwnPropertyNames() phuong thuc nay tra ve mang (including non-enumerable properties except for those which use Symbol) found directly in a given object.

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

Syntax

+ +
Object.getOwnPropertyNames(obj)
+ +

Parameters

+ +
+
obj
+
The object whose enumerable and non-enumerable properties are to be returned.
+
+ +

Return value

+ +

An array of strings that corresponds to the properties found directly in the given object.

+ +

Description

+ +

Object.getOwnPropertyNames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object obj. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a {{jsxref("Statements/for...in", "for...in")}} loop (or by {{jsxref("Object.keys()")}}) over the properties of the object. The ordering of the non-enumerable properties in the array and the ordering among the enumerable properties is not defined.

+ +

Examples

+ +

Using Object.getOwnPropertyNames()

+ +
var arr = ['a', 'b', 'c'];
+console.log(Object.getOwnPropertyNames(arr).sort());
+// logs ["0", "1", "2", "length"]
+
+// Array-like object
+var obj = { 0: 'a', 1: 'b', 2: 'c' };
+console.log(Object.getOwnPropertyNames(obj).sort());
+// logs ["0", "1", "2"]
+
+// Logging property names and values using Array.forEach
+Object.getOwnPropertyNames(obj).forEach(
+  function (val, idx, array) {
+    console.log(val + ' -> ' + obj[val]);
+  }
+);
+// logs
+// 0 -> a
+// 1 -> b
+// 2 -> c
+
+// non-enumerable property
+var my_obj = Object.create({}, {
+  getFoo: {
+    value: function() { return this.foo; },
+    enumerable: false
+  }
+});
+my_obj.foo = 1;
+
+console.log(Object.getOwnPropertyNames(my_obj).sort());
+// logs ["foo", "getFoo"]
+
+ +

If you want only the enumerable properties, see {{jsxref("Object.keys()")}} or use a {{jsxref("Statements/for...in", "for...in")}} loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with {{jsxref("Object.prototype.hasOwnProperty()", "hasOwnProperty()")}}).

+ +

Items on the prototype chain are not listed:

+ +
function ParentClass() {}
+ParentClass.prototype.inheritedMethod = function() {};
+
+function ChildClass() {
+  this.prop = 5;
+  this.method = function() {};
+}
+ChildClass.prototype = new ParentClass;
+ChildClass.prototype.prototypeMethod = function() {};
+
+console.log(
+  Object.getOwnPropertyNames(
+    new ChildClass() // ["prop", "method"]
+  )
+);
+
+ +

Get non-enumerable properties only

+ +

This uses the {{jsxref("Array.prototype.filter()")}} function to remove the enumerable keys (obtained with {{jsxref("Object.keys()")}}) from a list of all keys (obtained with Object.getOwnPropertyNames()) thus giving only the non-enumerable keys as output.

+ +
var target = myObject;
+var enum_and_nonenum = Object.getOwnPropertyNames(target);
+var enum_only = Object.keys(target);
+var nonenum_only = enum_and_nonenum.filter(function(key) {
+  var indexInEnum = enum_only.indexOf(key);
+  if (indexInEnum == -1) {
+    // Not found in enum_only keys,
+    // meaning that the key is non-enumerable,
+    // so return true so we keep this in the filter
+    return true;
+  } else {
+    return false;
+  }
+});
+
+console.log(nonenum_only);
+
+ +

Notes

+ +

In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, a non-object argument will be coerced to an object.

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

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-object.getownpropertynames', 'Object.getOwnPropertyNames')}}
+ +

Browser compatibility

+ + + +

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

+ +

Firefox-specific notes

+ +

Prior to Firefox 28, Object.getOwnPropertyNames did not see unresolved properties of {{jsxref("Error")}} objects. This has been fixed in later versions (bug 724768).

+ +

See also

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

The Object constructor creates an object wrapper.

+ +

Syntax

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

Parameters

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

Description

+ +

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().

+ +

See also the object initializer / literal syntax.

+ +

Properties of the Object constructor

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

Methods of the Object constructor

+ +
+
{{jsxref("Object.assign()")}} {{experimental_inline}}
+
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.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.getOwnPropertyNames()")}}
+
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
+
{{jsxref("Object.getOwnPropertySymbols()")}} {{experimental_inline}}
+
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()")}} {{experimental_inline}}
+
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.observe()")}} {{experimental_inline}}
+
Asynchronously observes changes to an object.
+
{{jsxref("Object.preventExtensions()")}}
+
Prevents any extensions of an object.
+
{{jsxref("Object.seal()")}}
+
Prevents other code from deleting properties of an object.
+
{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}
+
Sets the prototype (i.e., the internal [[Prototype]] property)
+
+ +

Object instances and Object prototype 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.

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
+ +

Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
+ +

Examples

+ +

Using Object given undefined and null types

+ +

The following examples store an empty Object object in o:

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

Using Object to create Boolean objects

+ +

The following examples store {{jsxref("Boolean")}} objects in o:

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

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
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')}} 
+ +

Browser compatibility

+ +
{{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}}
+
+ +

See also

+ + diff --git a/files/vi/web/javascript/reference/global_objects/object/observe/index.html b/files/vi/web/javascript/reference/global_objects/object/observe/index.html new file mode 100644 index 0000000000..f9074ea94e --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/observe/index.html @@ -0,0 +1,193 @@ +--- +title: Object.observe() +slug: Web/JavaScript/Reference/Global_Objects/Object/observe +tags: + - ECMAScript7 + - Experimental + - JavaScript + - Method + - Object +translation_of: Archive/Web/JavaScript/Object.observe +--- +
{{JSRef}}
+ +

Object.observe() được sử dụng để đồng bộ quan sát những thay đổi cho một đối tượng. Nó cung cấp một dòng thay đổi trong thứ tự mà chúng xảy ra.

+ +

Cú pháp

+ +
Object.observe(obj, callback[, acceptList])
+ +

Tham số

+ +
+
obj
+
Đối tượng được quan sát.
+
callback
+
Hàm được gọi mỗi lần có thay đổi trong obj, với những tham số sau: +
+
changes
+
Một mảng các đối tượng mô tả sự thay đổi. Mỗi đối tượng chứa các thuộc tính: +
    +
  • name: Tên thuộc tính đã thay đổi.
  • +
  • object: Đối tượng được thay đổi.
  • +
  • type: Một chuỗi cho biết loại thay đổi đang diễn ra. Có thể là "add", "update", hoặc "delete".
  • +
  • oldValue: Chỉ có cho loại "update" và "delete". Cho biết giá trị trước khi thay đổi.
  • +
+
+
+
+
acceptList
+
Danh sách các loại thay đổi được quan sát. Nếu bỏ qua, mặc định là ["add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions"].
+
+ +

Mô tả

+ +

Hàm callback được gọi mỗi khi có thay đổi trong obj, với một mảng các đối tượng chứa thông tin về sự thay đổi.

+ +

Ví dụ

+ +

Ghi lại tất cả sáu loại thay đổi khác nhau

+ +
var obj = {
+  foo: 0,
+  bar: 1
+};
+
+Object.observe(obj, function(changes) {
+  console.log(changes);
+});
+
+obj.baz = 2;
+// [{name: 'baz', object: <obj>, type: 'add'}]
+
+obj.foo = 'hello';
+// [{name: 'foo', object: <obj>, type: 'update', oldValue: 0}]
+
+delete obj.baz;
+// [{name: 'baz', object: <obj>, type: 'delete', oldValue: 2}]
+
+Object.defineProperty(obj, 'foo', {writable: false});
+// [{name: 'foo', object: <obj>, type: 'reconfigure'}]
+
+Object.setPrototypeOf(obj, {});
+// [{name: '__proto__', object: <obj>, type: 'setPrototype', oldValue: <prototype>}]
+
+Object.seal(obj);
+// [
+//   {name: 'foo', object: <obj>, type: 'reconfigure'},
+//   {name: 'bar', object: <obj>, type: 'reconfigure'},
+//   {object: <obj>, type: 'preventExtensions'}
+// ]
+
+ +

Ràng buộc dữ liệu

+ +
// Mô hình user
+var user = {
+  id: 0,
+  name: 'Brendan Eich',
+  title: 'Mr.'
+};
+
+// Lời chào tới user
+function updateGreeting() {
+  user.greeting = 'Hello, ' + user.title + ' ' + user.name + '!';
+}
+updateGreeting();
+
+Object.observe(user, function(changes) {
+  changes.forEach(function(change) {
+    // Bất kỳ khi nào tên hoặc danh hiệu thay đổi, gọi updateGreeting()
+    if (change.name === 'name' || change.name === 'title') {
+      updateGreeting();
+    }
+  });
+});
+
+ +

Loại thay đổi tùy chỉnh

+ +
// Một điểm trên một mặt phẳng
+var point = {x: 0, y: 0, distance: 0};
+
+function setPosition(pt, x, y) {
+  // Thực hiện thay đổi tùy chỉnh
+  Object.getNotifier(pt).performChange('reposition', function() {
+    var oldDistance = pt.distance;
+    pt.x = x;
+    pt.y = y;
+    pt.distance = Math.sqrt(x * x + y * y);
+    return {oldDistance: oldDistance};
+  });
+}
+
+Object.observe(point, function(changes) {
+  console.log('Distance change: ' + (point.distance - changes[0].oldDistance));
+}, ['reposition']);
+
+setPosition(point, 3, 4);
+// Distance change: 5
+
+ +

Đặc tả

+ +

Strawman proposal for ECMAScript 7.

+ +

Khả năng tương thích trình duyệt

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
Tính năngChromeFirefox (Gecko)Internet ExplorerOperaSafari
Hỗ trợ cơ bản{{CompatChrome("36")}}{{CompatNo}}{{CompatNo}}{{CompatOpera("23")}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
Tính năngAndroidChrome dành cho AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Hỗ trợ cơ bản{{CompatNo}}{{CompatChrome("36")}}{{CompatNo}}{{CompatNo}}{{CompatOpera("23")}}{{CompatNo}}
+
+ +

Xem thêm

+ + diff --git a/files/vi/web/javascript/reference/global_objects/object/tostring/index.html b/files/vi/web/javascript/reference/global_objects/object/tostring/index.html new file mode 100644 index 0000000000..78a46f1272 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/tostring/index.html @@ -0,0 +1,128 @@ +--- +title: Object.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Object/toString +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString +--- +
{{JSRef}}
+ +

Phương thức toString() trả về một chuỗi đại diện cho object.

+ +

Cú pháp

+ +
obj.toString()
+ +

Giá trị trả về

+ +

Một chuỗi đại diện cho object.

+ +

Miêu tả

+ +

Mỗi object có 1 phương thức toString(). Phương thức này được tự động gọi khi object được biểu diễn dưới dạng text hoặc trong bối cảnh mà một chuỗi được mong đợi để trả về. Mặc định, phương thức toString() được kế thừa cho tất cả object khi tất cả object được kế thừa từ Object. Nếu phương thức này không bị ghi đè bởi một object đã được tuỳ chỉnh, phương thức này trả về "[object type]", trong đó type là kiểu của object. Phần code theo sau mô tả điều này:

+ +
var o = new Object();
+o.toString(); // returns [object Object]
+
+ +
+

Note: Kể từ JavaScript 1.8.5, toString() khi được gọi trong {{jsxref("null")}} sẽ trả về [object Null], và {{jsxref("undefined")}} sẽ trả về [object Undefined], như đã được định nghĩa trong 5th Edition of ECMAScript and a subsequent Errata. Tham khảo {{anch("Using_toString()_to_detect_object_class", "Using_toString()_to_detect_object_class")}}.

+
+ +

Ví dụ

+ +

Ghi đè phương thức mặc định toString

+ +

Bạn có thể tạo một hàm để thay thể phương thức mặc định toString(). Phương thức mặc định toString() không có tham số truyền vào và sẽ trả về một chuỗi. Phương thức toString() bạn tự tạo có thể trả về bất kì giá trị gì bạn muốn, nhưng sẽ tốt hơn nếu nó mang thông tin về object.

+ +

Phần code sau đây định nghĩa kiểu Dog object và tạo ra theDog, một object của kiểu Dog:

+ +
function Dog(name, breed, color, sex) {
+  this.name = name;
+  this.breed = breed;
+  this.color = color;
+  this.sex = sex;
+}
+
+theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');
+
+ +

Nếu bạn gọi phương thức toString() trên object tuỳ chỉnh này, nó sẽ trả về giá trị mặc định được kế thừa từ {{jsxref("Object")}}:

+ +
theDog.toString(); // returns [object Object]
+
+ +

Phần code sau đây tạo ra và gán dogToString() để ghi đè lên phương thức mặc định toString(). Hàm này sẽ tạo một chuỗi chứa tên, giống, màu và giới tính của object, theo dạng "property = value;".

+ +
Dog.prototype.toString = function dogToString() {
+  var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed;
+  return ret;
+}
+
+ +

Với phần code ở phía trên, mỗi khi theDog được sử dụng để trả về một chuỗi, JavaScript sẽ tự động gọi hàm dogToString(), trả về kết quả sau:

+ +
"Dog Gabby is a female chocolate Lab"
+
+ +

Sử dụng toString() để xác định lớp đối tượng

+ +

toString() có thể được sử dụng với tất cả object và cho phép bạn xác định lớp của object đó. Để sử dụng Object.prototype.toString() với mọi đối tượng, bạn cần gọi {{jsxref("Function.prototype.call()")}} or {{jsxref("Function.prototype.apply()")}} trên object đó, truyền vào object mà bạn muốn vào tham số đầu tiên hay còn được gọi là thisArg.

+ +
var toString = Object.prototype.toString;
+
+toString.call(new Date);    // [object Date]
+toString.call(new String);  // [object String]
+toString.call(Math);        // [object Math]
+
+// Since JavaScript 1.8.5
+toString.call(undefined);   // [object Undefined]
+toString.call(null);        // [object Null]
+
+ +

Đặc tả

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}}{{Spec2('ES5.1')}}Call on {{jsxref("null")}} returns [object Null], and {{jsxref("undefined")}} returns [object Undefined]
{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}{{Spec2('ESDraft')}}
+ +

Tính tương thích với trình duyệt

+ +
+ + +

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

+
+ +

Tham khảo thêm

+ + diff --git a/files/vi/web/javascript/reference/global_objects/object/valueof/index.html b/files/vi/web/javascript/reference/global_objects/object/valueof/index.html new file mode 100644 index 0000000000..44a440e1f6 --- /dev/null +++ b/files/vi/web/javascript/reference/global_objects/object/valueof/index.html @@ -0,0 +1,108 @@ +--- +title: Object.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/valueOf +translation_of: Web/JavaScript/Reference/Global_Objects/Object/valueOf +--- +
{{JSRef}}
+ +

Phương thức valueOf() trả về giá trị nguyên thuỷ(primitive value) của object đang được nói tới.

+ +

Cú pháp

+ +
object.valueOf()
+ +

Giá trị trả về

+ +

Giá trị nguyên thuỷ(primitive value) của object đang được nói tới.

+ +

Miêu tả

+ +

JavaScript gọi phương thức valueOf để chuyển đổi một object sang một giá trị nguyên thuỷ. Bạn hiếp khi cần gọi phương thức valueOf bởi chính bạn; JavaScript tự động gọi nó khi gặp phải một object ở chỗ mà một giá trị nguyên thuỷ cần được trả về.

+ +

Mặc định, phương thức valueOf được kế thừa cho mọi object khi mà mọi object đó được kế thừa từ {{jsxref("Object")}}. Mọi core-object được tạo sẵn để ghi đè phương thức này để trả về giá trị phù hợp. Nếu một object ko có giá trị nguyên thuỷ, valueOf sẽ trả về chính object đó.

+ +

Bạn có thể sử dụng valueOf trong code của bạn để chuyển đổi một object được tạo sẵn thành một giá trị nguyên thuỷ. Khi bạn tạo một object tuỳ chỉnh, bạn có thể ghi đè Object.prototype.valueOf() để gọi phương thức tuỳ chỉnh thay vì phương thức mặc định {{jsxref("Object")}}.

+ +

Ghi đè valueOf cho object tuỳ chỉnh

+ +

Bạn có thể tạo một hàm để được gọi thay thể cho phương thức valueOf. Hàm của bạn phải không nhận tham số nào cả.

+ +

Giả sử bạn có một object loại MyNumberType và bạn muốn tạo một phương thức valueOf cho nó. Phần code sau đây gán một hàm định nghĩa bới người dùng cho phương thức valueOf của object:

+ +
MyNumberType.prototype.valueOf = function() { return customPrimitiveValue; };
+ +

 

+ +

Với phần code phía trên, mỗi khi một object loại MyNumberType được sử dụng trong bối cảnh mà nó cần được biểu diễn bởi một giá trị nguyên thuỷ, JavaScript sẽ tự động gọi hàm đã được viết trên đây.

+ +

Một phương thức valueOf của object thường được gọi bởi JavaScript, nhưng bạn có thể tự gọi nó bằng cách sau:

+ +
myNumberType.valueOf()
+ +
+

Note: Objects in string contexts convert via the {{jsxref("Object.toString", "toString()")}} method, which is different from {{jsxref("String")}} objects converting to string primitives using valueOf. All objects have a string conversion, if only "[object type]". But many objects do not convert to number, boolean, or function.

+
+ +

Ví dụ

+ +

Sử dụng valueOf

+ +
function MyNumberType(n) {
+    this.number = n;
+}
+
+MyNumberType.prototype.valueOf = function() {
+    return this.number;
+};
+
+var myObj = new MyNumberType(4);
+myObj + 3; // 7
+
+ +

Đặc tả

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.2.4.4', 'Object.prototype.valueOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}{{Spec2('ESDraft')}} 
+ +

Tính tương thích trình duyệt

+ +
+ + +

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

+
+ +

See also

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