JavaScript | Object.defineProperties() 方法
JavaScript 中的Object.defineProperties() 方法是标准内置对象,它直接在对象上定义新属性或修改现有属性并返回该对象。
句法:
Object.defineProperties(obj, props)
范围:
- Obj:此参数保存要在其上定义或修改属性的对象。
- Props:此参数是一个对象,其自身的可枚举属性构成要定义或修改的属性的描述符。
返回值:此方法返回一个作为参数传递给函数的对象。
下面的示例说明了 JavaScript 中的 Object.defineProperties() 方法:
示例 1:
javascript
const geek = {};
Object.defineProperties(geek, {
prop1: {
value: "geeksforgeeks",
writable: true
},
prop2: {}
});
console.log(geek.prop1);
console.log(geek.prop2);
javascript
var geek = {};
Object.defineProperties(geek, {
'prop1': {
value: "Geeks",
writable: true
},
'prop2': {
value: 'Hello',
writable: false
}
});
console.log(geek.prop2);
console.log(geek.prop1);
const geek1 = {};
Object.defineProperties(geek1, {
prop1: {
value: "Hi",
value: "Hello",
value: "Namaste",
},
prop2: {
value: " And ", },
prop3: {
value: "learn",
value: "Stay Safe", }
});
console.log(geek1.prop1, geek1.prop2, geek1.prop3);
输出:
"geeksforgeeks"
undefined
示例 2:
javascript
var geek = {};
Object.defineProperties(geek, {
'prop1': {
value: "Geeks",
writable: true
},
'prop2': {
value: 'Hello',
writable: false
}
});
console.log(geek.prop2);
console.log(geek.prop1);
const geek1 = {};
Object.defineProperties(geek1, {
prop1: {
value: "Hi",
value: "Hello",
value: "Namaste",
},
prop2: {
value: " And ", },
prop3: {
value: "learn",
value: "Stay Safe", }
});
console.log(geek1.prop1, geek1.prop2, geek1.prop3);
输出:
"Hello"
"Geeks"
"Namaste" " And " "Stay Safe"
支持的浏览器: Object.defineProperties() 方法支持的浏览器如下:
- 谷歌浏览器 6.0 及以上
- Internet Explorer 9.0 及更高版本
- Mozilla 4.0 及更高版本
- Opera 11.1 及更高版本
- Safari 5.0 及以上