Question related to Object.extendsObject()

alisha4
Kilo Explorer

HI ALL,

I have gone through the prototype js docs.,but there is no function "extendObject()" defined for Object.

Object.extendsObject();

Please tell me.

7 REPLIES 7

The SN Nerd
Giga Sage
Giga Sage

The Script Include PrototypeServer shows what the code does. It is custom to ServiceNow to mimic OO in JavaScript.


It just copies all the functions and global variables of the class you are extending into the Script Includes so you can use them in your object.



Object.extendsObject = function(destination, source) {


  destination = Object.clone(destination.prototype);


 


  for (var property in source) {


      destination[property] = source[property];


  }


  return destination;


}




Object.clone = function(obj) {


  var clone = Class.create();



  for (var property in obj) {


      clone[property] = obj[property];


  }



  return clone;


}



ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022

And it does a bad job of it.  What I'm wondering is if they're avoiding pointers and references to avoid something worse than broken inheritance?

The following works, but does anyone know of hidden rhino dragons I may be tempting fate with?

 

var extendClassy = function (parentClass, childPrototype) {
  /* returns child prototype */
  var rproto = (gs.nil(childPrototype))?{}:childPrototype;
  /* Don't know if they avoid prototype chaining for a reason? */
  // rproto.prototype = parentClass.prototype ;
  for (var property in parentClass.prototype){
    if (gs.nil(Object.getOwnPropertyDescriptor(rproto,property))){
      Object.defineProperty(rproto,property,
          Object.getOwnPropertyDescriptor(parentClass.prototype,property)
      );
    }
  }
  return rproto;  
};

var asdf = Class.create();
asdf.prototype={
  initialize: function(s){
    this._v=s
  },
  get value(){
    return this._v ;
  },
  type: "asdf"
};

var ClassyExtended = Class.create();
ClassyExtended.prototype = extendClassy(asdf,{type: "ClassyExtended"});

var DumbExtended = Class.create();
DumbExtended.prototype = Object.extendsObject(asdf,{type: "DumbExtended"});

gs.print( (new ClassyExtended("hello world")).value ); 
// -> hello world

gs.print( (new DumbExtended("hello world")).value );
// -> undefined

BillMartin
Mega Sage

Hi @alisha4 ,

 

I have created this easy to follow example where you can inherit from a class using Object.extendsObject() function. 

 

You can find more details here: Master Good Software Architecture with Object.extendsObject() | A Guide for ServiceNow Developers