Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Friday, January 1, 2016

Javascript object extending -

Javascript object extending -


I am currently transforming from Java to Javascript, and it's a bit hard for me to figure out how to extend objects the way I want it to do.

I've seen several people on the internet, which has a method on object called extend. The code will look like this:

var Person = {     name : 'Blank',     age  : 22  }    var Robot = Person.extend({     name : 'Robo',     age  : 4  )}    var robot = new Robot();  alert(robot.name); //Should return 'Robo'  

Does anyone know how to make this work? I've heard that you need to write

Object.prototype.extend = function(...);  

But I don't know how to make this system work. If it is not possible, please show me another alternative that extends an object.

Answer by osahyoun for Javascript object extending -


Edit:
Before using the code, please check the comments from user2491400 that reports about the side effects of simply assigning to prototype.

Original answer:

You want to 'inherit' from Person's prototype object:

var Person = function(name){    this.name = name;    this.type = 'human';  }    Person.prototype.info = function(){    console.log("Name:", this.name, "Type:", this.type);  }    var Robot = function(name){    Person.apply(this,arguments)    this.name = name;    this.type = 'robot';  }    Robot.prototype = Person.prototype;        // Set prototype to Person's  Robot.prototype.constructor = Robot;   // Set constructor back to Robot    person = new Person("Bob");  robot = new Robot("Boutros");    person.info();  // Name: Bob Type: human    robot.info();  // Name: Boutros Type: robot  

Answer by 250R for Javascript object extending -


You might want to consider using helper library like underscore.js http://documentcloud.github.com/underscore/#extend

And it's also a good way to learn by looking at it's source code. The annotated source code page is quite useful http://documentcloud.github.com/underscore/docs/underscore.html

Answer by tomilay for Javascript object extending -


If you haven't yet figured out a way, use the associative property of JavaScript objects to add an extend function to the Object.prototype as shown below.

    Object.prototype.extend = function(obj) {         for (var i in obj) {            if (obj.hasOwnProperty(i)) {               this[i] = obj[i];            }         }      };  

You can then use this function as shown below.

    var o = { member: "some member" };      var x = { extension: "some extension" };        o.extend(x);  

Answer by Harold for Javascript object extending -


And another year later, I can tell you there is another nice answer.

If you don't like the way prototyping works in order to extend on objects/classes, take alook at this: https://github.com/haroldiedema/joii

Quick example code of possibilities (and many more):

var Person = Class({        username: 'John',      role: 'Employee',        __construct: function(name, role) {          this.username = name;          this.role = role;      },        getNameAndRole: function() {          return this.username + ' - ' + this.role;      }    });    var Manager = Class({ extends: Person }, {      __construct: function(name)    {        this.super('__construct', name, 'Manager');    }    });    var m = new Manager('John');  console.log(m.getNameAndRole()); // Prints: "John - Manager"  

Answer by user1216998 for Javascript object extending -


Prototyping is a nice way, but prototype is quite dangerous sometimes and can lead to bugs. I prefer to encapsulate this into a base object, like Ember.js does to it's Ember.Object.extend and Ember.Object.reopen. That is much more secure to use.

I created a gist with how you would setup something similar to what Ember.Object uses.

Here's the link: https://gist.github.com/WebCloud/cbfe2d848c80d4b9e9bd

Answer by Lior Elrom for Javascript object extending -


Object.create

Per @osahyoun answer, I find the following as a better and efficient way to 'inherit' from Person's prototype object:

function Person(name){      this.name = name;      this.type = 'human';  }  Person.prototype.info = function(){      console.log("Name:", this.name, "Type:", this.type);  }    function Robot(name){      Person.call(this)      this.type = 'robot';  }    // Set Robot's prototype to Person's prototype  Robot.prototype = Object.create(Person.prototype);    // Set constructor back to Robot  Robot.prototype.constructor = Robot;    person = new Person("Bob");  robot = new Robot("Boutros");    person.info(); // Name: Bob Type: human  robot.info();  // Name: Boutros Type: robot  

Now, by using Object.create, Person.prototype.constructor !== Robot

Check also the MDN documentation.

Answer by Calvintwr for Javascript object extending -


World without the "new" keyword.

And simpler syntax with Object.create().

I'm in the camp that believes Javascript should try to live without "new". It is a classless language, it doesn't need constructors. You simply create Objects and then extend or morph them. Granted, there are pitfalls, but this is so much more powerful and simple:

// base `Person` prototype  var Person = {     name : '',     age  : 22,     type : 'human',     greet: function() {         console.log('Hi, my name is ' + this.name + ' and I am a ' + this.type + '.' );     }  };    // create an instance of `Person`:  var skywalker = Object.create(Person);  skywalker.name = 'Anakin Skywalker';  skywalker.greet(); // 'Hi, my name is Anakin Skywalker and I am a human.'  

Extending the base prototype

// create a `Robot` prototype by extending the `Person` prototype:  var Robot = Object.create(Person);  Robot.type = 'robot';  Robot.variant = ''; // add properties for Robot prototype    // Robots speak in binaries, so we need a different greet function:  Robot.greet = function() { //some function to convert strings to binary }  

One more level deeper

// create a new instance `Robot`  var Astromech = Object.create(Robot);  Astromech.variant = 'astromech';    var rd2d = Object.create(Astromech);  r2d2.name = 'R2D2';  r2d2.greet(); // '0000111010101011100111....'    // morphing the `Robot` object doesn't affect `Person` prototypes  skywalker.greet(); // 'Hi, my name is Anakin Skywalker and I am a human.'  

Further reading

Often people create an #extend() method to allow easier extension. It basically allows you to create the new several properties with one statement:

function extend(obj, props) {      for(var prop in props) {          if(props.hasOwnProperty(prop)) {              obj[prop] = props[prop];          }      }  }    //using our own extend function  var Robot = Object.create(Person);  extend(Robot, {      madeOf: "metal",      powerConsumption: "5kWh"  });    //instead of  Robot.madeOf = "metal";  Robot.powerConsumption: "5kWh";    //you can also use Object.create()'s second argument a.k.a propertiesObject,  //which I find to be a little too lengthy  var Robot = Object.create(Person, {      madeOf: {           value: "metal",          writable: true,          configurable: true,          enumerable: true      },      powerConsumption: {          value: "5kWh",          writable: true,          configurable: true,          enumerable: true         }  });  

There are gotchas to this pattern that are likely to trip "classical-trained" programmers. Nonetheless, I find this pattern so much more readable.

Answer by Abdennour TOUMI for Javascript object extending -


Function.prototype.extends=function(ParentClass) {      this.prototype = new ParentClass();      this.prototype.constructor = this;  }  

Then :

function Person(){    this.name="anonym"    this.skills=["abc"];   }  Person.prototype.profile=function(){return this.skills.length} ;//1    function Student(){} //well extends fom Person Class  Student.extends(Person)    var s1=new Student();  s1.skills.push("")                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    s1.profile() //2  

Answer by Cezary Daniel Nowak for Javascript object extending -


In the majority of project there are some implementation of object extending: underscore, jquery, lodash: extend.

There is also pure javascript implementation, that is a part of ECMAscript 6: Object.assign: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Answer by Niek Vandael for Javascript object extending -


Mozilla 'announces' object extending from ECMAScript 6.0:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends

NOTE: This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.

class Square extends Polygon {    constructor(length) {      // Here, it calls the parent class' constructor with lengths      // provided for the Polygon's width and height      super(length, length);      // Note: In derived classes, super() must be called before you      // can use 'this'. Leaving this out will cause a reference error.      this.name = 'Square';    }      get area() {      return this.height * this.width;    }      set area(value) {      this.area = value;     }   }  

This technology is available in Gecko (Google Chrome / Firefox) - 03/2015 nightly builds.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.