Object.create()

  • Object.create() este o metoda statica care creaza un nou obiect cu prototype-ul setat la un obiect anume
const cat={
 makeSound: function() {
  console.log('miau');
  }
}

cat.makeSound(); //miau
const cat={
 makeSound: function() {
  console.log(this.sound);
  }
}

const mark= Object.create(cat);// creaza un nou obiect si va seta prototipul
 acelui obiect sa fie cat
mark.sound= 'miau';

mark.makeSound(); //miau

console.log('Is mark a cat?', cat.isPrototypeOf(mark)); //true

-Object.create() este de preferat pt prototype model in locul new

const cat={
 init: function(sound){
  this.sound= sound
 }
 makeSound: function() {
  console.log(this.sound);
  }
}

function objectCreate(proto) {
  const obj ={}
  Object.setprototypeOf(obj, proto);
  return obj;
}

const mark= objectCreate(cat);// creaza un nou obiect si va seta prototipul
 acelui obiect sa fie cat
mark.init= 'miau';

mark.makeSound(); //miau

console.log('Is mark a cat?', cat.isPrototypeOf(mark)); //true

Concluzii:

-Object.create() este o metoda statica care creaza un nou obiect cu prototype-ul setat la un obiect anume

__proto__ vs prototype

let cat = { breed: 'munchkin'}
let myCat ={ name: 'Sisi'}

Object.setPrototype(myCat, cat);

myCat.name(); // Sisi
myCat.breed();// munchkin
myCat.__proto__ // {breeed: 'munchkin'}, o referinta pt acel obiect

cat.tailLength =15;
myCat.__proto__ // {breeed: 'munchkin', tailLength: 15}
myCat.tailLength //15

– delegarea obiectelor catre alte obiecte

-prototype e pt functii

function Dog(){}

Dog.prototype.breed= 'Bulldog';
let myDog= new Dog();

myDog.breed;// 'Bulldog'

myDog.__proto__ ; // {breed: 'Bulldog'}
myDog.prototype; //undefined
Dog.prototype; // {breed:'Bulldog'} , a fost setat mai sus

function Giraffe() {};
Giraffe.prototype;// {}

let koala= {}
koala.prototype; // undefined
koala.__proto__ ; // {}
koala.__proto__== Object.prototype; //true
Object.prototype.sleep ='zzzzzz';
koala.sleep; //zzzzzz

Concluzii:
__proto__ este proprietatea care pe un obiect, pointeaza catre prototipul care a fost setat

prototype este proprietatea pe o functie, care este setat ca proprietatea daca se foloseste  new

Design a site like this with WordPress.com
Get started