Uczę się javascript (pochodzącego z php) i widzę, że istnieje wiele sposobów tworzenia klas. Nauczyłem się również o magicznych metodach, takich jak get i set, i zastanawiam się, jak można je tworzyć w różnych scenariuszach (oprócz robienia tego podczas tworzenia klasy ze słowem kluczowym class). Opublikowałem również sposób robienia gettera i settera w literale obiektowym i zastanawiałem się, czy jest łatwiejszy sposób. Oto kod
//-------------------------------------------------------------------
//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??
0
Vukasin Sevo
22 listopad 2018, 17:37
1 odpowiedź
Najlepsza odpowiedź
Dodanie gettera/settera w obiekcie:
let objLit = {
name: 'asas',
name2: 'assad',
get name3() {
return this._name3
},
set name3(value) {
this._name3 = value
}
}
W funkcji fabrycznej:
function createObj(param1, param2) {
return {
set name1(value) {
param1 = value
},
set name2(value) {
param2 = value
},
get fullName() {
return `${param1} {param2}`
}
}
}
0
Nathan Xabedi
22 listopad 2018, 18:52