javascript - Javascript在不同场景中添加setter
问题描述
我正在学习 javascript(来自 php)并看到有多种创建类的方法。还了解了 get 和 set 之类的魔术方法,我想知道如何在不同的场景中创建它们(除了在使用 class 关键字创建类时这样做)。我还发布了在对象文字中执行 getter 和 setter 的方法,并且想知道是否有更简单的方法。这是代码
//-------------------------------------------------------------------
//class
class create{
constructor(param1,param2){
this.name = param1;
this.name2 = param2;
}
fullname(){
console.log('...');
}
set name3(enteredValue){
this._name3 = enteredValue;
}
get name3(){
return this._name3;
}//This is how it is done in class
}
var obj2 = new create('test','test');
//-------------------------------------------------------------------
//object literal
var objLit = {
name: 'asas',
name2: 'assad'
}
Object.defineProperty(objLit, 'name3', {
get : function(){
return this._name3;
},
set : function(value){
this._name3 = value;
}
}); //This is how it is done in obj literal / Is there other way to do it in object?
//-------------------------------------------------------------------
//Factory Function
function createObj(param1, param2){
return{
name1: param1,
name2: param2,
fullName: function(){
console.log(this.name1+' '+this.name2);
}
}
}
var obj3 = createObj('Vukasin','Miljan');
//How to add setter in this scenario?
//-------------------------------------------------------------------
//Constructor function
function createObj2(param1,param2){
this.name1 = param1;
this.name2 = param2;
}
var obj4 = new createObj2('..','..');
//How to add setter in this scenario??
解决方案
在对象中添加 getter/setter:
let objLit = {
name: 'asas',
name2: 'assad',
get name3() {
return this._name3
},
set name3(value) {
this._name3 = value
}
}
在工厂函数中:
function createObj(param1, param2) {
return {
set name1(value) {
param1 = value
},
set name2(value) {
param2 = value
},
get fullName() {
return `${param1} {param2}`
}
}
}
推荐阅读
- python - 是否有可能对重合线进行分组以评估线“密度”?
- c# - Auth0:根据范围限制访问
- laravel - Laravel 异常抛出
- python - 合并嵌套字典列表
- python - 删除收盘价
- visual-studio - Visual Studio Code 的终端中是否有“全选”的键盘快捷键?
- android - 多个模块中的Android DataBinding自定义适配器
- c# - 如何在 gRPC 通信中的 proto 3 有效负载中添加接口和类
- ruby-on-rails - 如何通过猴子补丁添加模型属性字段?
- azure - Azure Devops - 如何从发布管道选项中的下拉列表中添加额外的部署类型