se162xg / notes

1 stars 1 forks source link

JavaScript Object #11

Open se162xg opened 4 years ago

se162xg commented 4 years ago

Accessors

//Getter
var person = {
    language:"Chinese",
    get lang () {
        return this.language;
    }
}
// access "lang" as a property
person.lang
//Setter
var person = {
    language:"Chinese",
    set lang(x) {
        this.language = x
    }
}
person.lang = "English"
//Another way to add Getters and Setters
var obj = {counter : 0};
Object.defineProperty(obj, "increment", {
  get : function () {this.counter++;}
});
Object.defineProperty(obj, "add", {
  set : function (value) {this.counter += value;}
});
se162xg commented 4 years ago

Constructor

// constructor function
function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

All objects inherit properties and methods from a prototype, obj.prototype.

//prototype allows you to add new properties to objects constructor
function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";

//to add new methods
Person.prototype.name = function() {
  return this.firstName + " " + this.lastName;
};
se162xg commented 4 years ago

Constructor:evaluate js code

>> var a = 0["constructor"]
<   ƒ String() { [native code] }
>> a()
<   0

>> var b = 0["constructor"]["constructor"]
<   ƒ Function() { [native code] }
>> b("console.log(7*7)")
<   ƒ anonymous(
     ) {
         console.log(7*7)
     }
>> b("console.log(7*7);return 1")()
<   49
<   1

or 

>> 0["constructor"]["constructor"]("console.log(7*7)")()