Professional Documents
Culture Documents
Prototypes
Prototypes
var myCat = {
name: "pussy",
color:"white",
speak: function(){
console.log("Meeeow")
}
}
myCat // object
myCat.speak() // "Meeeow"
-----------
"use strict";
var cat = {
name: "pussy",
color: "white"
}
Object.defineProperty(cat,"name",{writable:false})
cat.name = "cool"
// throws an error
-------------
"use strict";
var cat = {
name: {fname:"sam",lname:"sahoo"},
color: "white"
}
Object.defineProperty(cat,"name",{writable:false})
cat.name = "cool" // throws and error
----------------
if we do something
Object.freeze(cat.name) // we can't change cat.name.fname value also
----------------
if we make configurable to "false"
-------------
getters and setters
"use strict"
var cat = {
name: {fname:"sam",lname:"sahoo"},
color: "white"
}
Object.defineProperty(cat,"fullname",{
get: function(){
return this.name.fname + " " + this.name.lname; // "sam sahoo"
},
set: function(value){
var nameParts = value.split(" ");
this.name.fname = nameParts[0];
this.name.lname = nameParts[1];
}
})
------------------
arr.last
arr2.last
**************************
So what is a prototype?
***********
function Cat(name,color){
this.name = name;
this.color = color;
}
Cat.prototype.age = 12;
myCat1.age = 30;
myCat1.age // 30
myCat1.__proto__.age // 12
myCat2.age // 12
myCat2.hasOwnProperty("age") // false
myCat1.hasOwnProperty("age") // true
////
function Animal(){
}
Animal.prototype.speak = function(){
console.log("meaowww")
}
function Cat(name,color){
this.name = name;
this.color = color;
}
Cat.prototype = Object.create(Animal.prototype)
myCat = new Cat("pussy","white");
myCat.speak() // meaowww
*********************
function Animal(voice){
this.voice = voice || "meaowww"
}
Animal.prototype.speak = function(){
console.log(this.voice)
}
function Cat(name,color){
Animal.call(this,"gerrrrr")
this.name = name;
this.color = color;
}
Cat.prototype = Object.create(Animal.prototype)
myCat = new Cat("pussy","white");
myCat.speak() // gerrrrr
console.log(myCat.constructor) // animal
console.log(myCat.__proto__) // Cat{}
console.log(myCat.__proto__.__proto__) // Animal{}
*******************
Class Pattern
"use strict";
class Cat{
constructor(name,color){
this.name = name;
this.color = color;
}
speak(){
console.log("Meeeow")
}
}
var myCat = new Cat("pussy","white");
Class Pattern - 2
"use strict";
class Animal{
constructor(voice){
this.voice = voice || "meaowww"
}
speak(){
console.log(this.voice)
}
}
-----------------------------------------------------------------------------------
-----------------------
var obj1 = {
name : "dasd"
}
********
Object.create()
obj2 = Object.create(obj1);