Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are quite a few generic methods to do that. I will provide three of them:</p> <p>1.) Using Function object as a constructor and as a prototype object for inherited new objects. The implementation should look like as the following:</p> <pre class="lang-js prettyprint-override"><code>var person = { toString : function() { return this.firstName + ' ' + this.lastName; } } function extend(constructor, obj) { var newObj = Object.create(constructor); for (var prop in obj) { if (obj.hasOwnProperty(prop)) { newObj[prop] = obj[prop]; } } return newObj; } var man = extend(person, { sex: "male", age: "22" }); var name = extend(man, { firstName: "Simo", lastName: "Endre" }); name.man; name.toString(); </code></pre> <p>2.) In this case we'll use the Function object as the constructor for simulating the classical inheritance in a language like C# or Java. The prototype property of an object will be used in the role of a constructor and the the newly created object will inherit all the properties from the object prototype root. In this case the object's prototype has only one kind of augmentation role, the effective implementation is done in the function method.</p> <pre><code>var Person = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } Person.prototype.toString = function() { return this.firstName + ' ' + this.lastName; } function inherit(func) { // passing function arguments into an array except the first one which is the function object itself var args = Array.prototype.slice.call(arguments, 1); // invoke the constructor passing the new Object and the rest of the arguments var obj = Object.create(func.prototype); func.apply(obj, args); //return the new object return obj; } var man = inherit(Person, "Simo", "Endre"); man.toString(); </code></pre> <p>3.) The well known inheritance model:</p> <pre><code>function extend(o) { function F() {} // We'll set the newly created function prototype property to the object. //This act as a constructor. F.prototype = o; // Using the `new` operator we'll get a new object whose prototype is o. return new F(); }; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload