New keyword

  • “new” aplicat functiilor
function Person(saying){
  this.saying= saying;
}

person.prototype.talk = function(){
  console.log('I say:', this.saying);
}

var pers1= new Person('blablabla');

pers1.talk(); //va afisa 'I say:blablabla'

  • creaza un nou obiect,
  • seteaza prototype-ul
  • executa contructorul cu this
  • retuneaza obiectul creat
function Person(saying){
  this.saying= saying;
}

person.prototype.talk = function(){
  console.log('I say:', this.saying);
}

function new1(contructor){
  var obj={};
  Object.setPrototypeOf(obj, contructor.prototype);
  var argsArray= Array.prototype.slice.appaly(arguments);
  constructor.apply(obj, argsArray.slice(1));
  return obj;
}

var pers1= new1(Person,'blablabla');

pers1.talk(); //va afisa 'I say:blablabla'

Daca constructorul retuneaza un obiect:

function Person(saying){
  this.saying= saying;
  return {
   myObj: true
  }
}

person.prototype.talk = function(){
  console.log('I say:', this.saying);
}

function new1(contructor){
  var obj={};
  Object.setPrototypeOf(obj, contructor.prototype);
  var argsArray= Array.prototype.slice.appaly(arguments);
  return constructor.apply(obj, argsArray.slice(1)) || obj;
}

var pers1= new1(Person,'blablabla');
console.log('hello', pers1); //hello {myObj:true}

Concluzii:

new:

  • creaza un nou obiect,
  • seteaza prototype-ul
  • executa contructorul cu this
  • retuneaza obiectul creat
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s