sách gpt4 ai đã đi

javascript - javascript中如何防止对象属性不被扩展

In lại 作者:行者123 更新时间:2023-12-03 05:33:50 hai mươi bốn 4
mua khóa gpt4 Nike

我正在尝试密封一个对象属性。

我的问题是,这里我给出了 Object.seal(personObject),这个特定的对象是密封的,不允许在这个对象中配置或进行任何扩展,但由于我没有提到 personObject_2 它确实允许扩展或配置

我怎样才能在原型(prototype)上实现它。我的意思是像任何类型的人都应该拥有/尊重这个印章。我们可以实现这样的行为

"use strict";
var personModule=(function (module) {
var person=function (fname,lname) {
Object.defineProperty(this,'firstName',{
get:function () {
return fname;
}
,set:function (newValue) {
fname=newValue;
},
configurable:true
});

Object.defineProperty(this,'lastName',{
get:function () {
return lname;
}
,set:function (newValue) {
lname=newValue;
},
configurable:true
});

Object.defineProperty(this,'fullName',{
get:function () {
return fname+lname;
},
configurable:true
});

}
module.person=person;
return module;
})(personModule || {});

var personObject=new personModule.person( "Raju","Rani");
console.log(personObject.fullName);
Object.seal(personObject);
//delete personObject.firstName;-->It throws error here




var personObject2=new personModule.person( "Shiva","Kumar");

delete personObject2.firstName;

console.log(personObject2.firstName);

Cảm ơn

1 Câu trả lời

这里是代理版本,以防您不喜欢在构造函数上添加 Object.seal

"use strict";
var personModule=(function (module) {
var person=function (fname,lname) {
Object.defineProperty(this,'firstName',{
get:function () {
return fname;
}
,set:function (newValue) {
fname=newValue;
},
configurable:true
});

Object.defineProperty(this,'lastName',{
get:function () {
return lname;
}
,set:function (newValue) {
lname=newValue;
},
configurable:true
});

Object.defineProperty(this,'fullName',{
get:function () {
return fname+lname;
},
configurable:true
});

}
module.person=new Proxy(person, {
construct(target, args){
args.unshift(null);
let ctor = target.bind.apply(target, args);
let result = new ctor();
Object.seal(result);
trả về kết quả;
}
});
return module;
})(personModule || {});

var personObject=new personModule.person( "Raju","Rani");
console.log(personObject.fullName);
Object.seal(personObject);
//delete personObject.firstName;-->It throws error here




var personObject2=new personModule.person( "Shiva","Kumar");

delete personObject2.firstName;

console.log(personObject2.firstName);

关于javascript - javascript中如何防止对象属性不被扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40816029/

hai mươi bốn 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com