JS- object constructor

blossom0417
1 min readOct 5, 2018

--

#new object()

var person = new object();
person.firstname = 'default';
person.lastname = 'default';
person.getFullName = function(){
return firstname + ' ' + lastname;
}

#literal notation

var person = {
firstname : 'default',
lastname : 'default',
getFullName: function(){
return firstname + '' + lastname;
}
}

#function constructor and prototyping

function PersonFn(firstname,lastname){
this.firstname = firstname;
this.lastname = lastname;

this.getFullName = function(){
return this.firstname + ' ' + this.lastname;
}
}
personFn.prototype.changeName = function(firstname, lastname){

this.firstname = firstname;
this.lastname = lastname;
//return this.firstname + ' ' + this.lastname;
}

//eunsim kang
var person1 = new personFn('eunsim','kang');
console.log(person1.getFullName()); // eunsim kang
person1.changeName('blossom','kang')
console.log(person1.getFullName()) // blossom kang

#calculator

function Calculator() {
//this.a, this.b;
this.read = function() {
this.a = Number(window.prompt("a?",0));
this.b = Number(window.prompt("b?",0));
return [this.a , this.b];
}
this.sum = function(){
return this.a + this.b
}
this.mul = function(){
return this.a * this.b
}

}
var calc = new Calculator();
calc.read();
console.log(calc.sum());
console.log(calc.mul());

#ref

https://javascript.info/constructor-new#create-new-calculator

--

--

No responses yet