Inherit parent constructor arguments - javascript

I'm browsing the discussion for a similar topic, but can't find my situation...
Am trying call parent constructors with parameters... can't seem to get it right.
I have a PhysicsBody superclass that takes aNode as its only constructor argument:
function PhysicsBody(aNode) {
this.userData = aNode;
// ...
}
Of this PhysicsBody inherits a DynamicBody class. Is constructor also takes aNode as only argument... Like I would do it in Java, I'd love to call something equivalent to "super(aNode"); Can't seem to find out how.
Here's the DynamicBody class:
// Wanted to give "new PhysicsBody(this, aNode)", but that fails!
DynamicBody.prototype = new PhysicsBody();
DynamicBody.prototype.constructor=DynamicBody;
function DynamicBody(aNode) {
// calling the parent constructor fails too:
// PhysicsBody.prototype.constructor.call(this, aNode);
//...
}

One way to do it:
function PhysicsBody( aNode ) {
this.userData = aNode;
}
PhysicsBody.prototype.pbMethod = function () {};
function DynamicBody( aNode ) {
PhysicsBody.call( this, aNode );
}
// setting up the inheritance
DynamicBody.prototype = Object.create( PhysicsBody.prototype );
DynamicBody.prototype.dbMethod = function () {};
Now, when you do
var pb = new PhysicsBody( '...' );
the instance pb gets a userData property and also inherits the methods from PhysicsBody.prototype (pbMethod in this case).
When you do
var db = new DynamicBody( '...' );
the instance db gets a userData property and also inherits the methods from DynamicBody.prototype (dbMethod in this case), which in turn inherits from PhysicsBody.prototype.

If I understand you correctly, by saying you want to inherit the parent constructor arguments, you mean that new DynamicBody(1, 2, 3) will internally call PhysicsBody(1, 2, 3) for the DynamicBody instance.
This can be accomplished by using .apply and passing arguments along: http://jsfiddle.net/pmkrQ/.
function DynamicBody() {
PhysicsBody.apply(this, arguments);
}

Related

JS Inheritance: calling the parent's function from within the child's function

There must be something I don't understand about the JS object model.
From these resources:
Prototypes
Basic OOP in JS- Inheritance
Object.create()
I have gathered what I think, or thought, was an accurate mental representation of the object model. Here it is:
All objects have a property, which the docs refer to as [[Prototype]]. [[Prototype]] can be thought of as a reference to the object's parent. More accurately:
The reference to the [parent's] prototype object is copied to the
internal [[Prototype]] property of the new instance. (source 1)
You can get access to the [[Prototype]] property of the child with Object.getPrototypeOf(child) The value returned here will be a reference to the parent's prototype (not its internal [[Prototype]] property, but its actual prototype)
obj.prototype is different from the object's internal [[Prototype]] property. It acts like the blueprints used to make instances of this exact object, while its [[Prototype]] property points to the blueprints used to make instances of its parent.
Parent.prototype === Object.getPrototypeOf(child); //true
To elaborate:
If you add a function to child.prototype the function will be available to child and any of it's children.
If you add a function to parent.prototype, which is equivalent to adding a function to Object.getPrototypeOf(child), then the function will be available to parent and all of it's children, which includes child and all of its siblings.
You can use Object.create() to create a new object with whatever [[Protoype]] property you want. So you can use it as a way to implement inheritance. See source 2 for an example.
With this in mind, I wanted to get a working example of my own going. My plan was to create a parent 'class' and then make a child 'class' that inherited from it.
I wanted the child class to implement a method, which overloaded a method from the parent. The caveat is that I want the child's version of the method to call the parent's version of the method and then do some extra stuff.
Here is what I came up with, see below for the issues associated with it:
var Parent = function() {};
Parent.prototype.myF = function() {
console.log('derp');
};
function Child() {
Parent.call(this);
};
//make [[prototype]] of Child be a ref to Parent.prototype
Child.prototype = Object.create(Parent.prototype);
//need to explicitly set the constructor
Child.prototype.constructor = Child;
Child.prototype.myF = function() {
Object.getPrototypeOf(this).myF();
console.log("did I derp??");
};
childInstance = new Child();
childInstance.myF();
It appears to be the case that when I attempt to overload Parent.myF(), while I am overloading it, I am actually modifying the original function at the same time. This appears to be the case because the logged results are:
'derp'
'did I derp??'
'did I derp??'
presumably the first occurance of 'did I derp??' is coming from a modified version of the parent's function, which I don't mean to do, then the second version is coming from the child's function.
Can anyone elaborate on why this is happening?
Great question, it took a bit of testing and researching to find it out.
Identifying the strange behaviour
I changed your code a little bit to find out which function is called when:
var Parent = function() {};
Parent.prototype.myF = function() {
console.log('derp');
};
function Child() {
Parent.call(this);
this.name = 'Test'; // this is a new test property
};
//make [[prototype]] of Child be a ref to Parent.prototype
Child.prototype = Object.create(Parent.prototype);
//need to explicitly set the constructor
Child.prototype.constructor = Child;
Child.prototype.myF = function() {
console.log(this); // here I want to find out the context, because you use it in the next line
Object.getPrototypeOf(this).myF();
console.log("did I derp??");
};
childInstance = new Child();
childInstance.myF();
You can check out the JSFiddle and try it for yourself: http://jsfiddle.net/Lpxq78bs/
The crucial line in your code is this:
Child.prototype.myF = function() {
Object.getPrototypeOf(this).myF(); // this one
console.log("did I derp??");
};
After doing a console.log(this); to find out what this refers to, I saw that it changes between the first and the second output of did I derp??.
I got the following output:
Object { name: "Test" }
Object { constructor: Child(), myF: window.onload/Child.prototype.myF() }
"derp"
"did I derp??"
"did I derp??"
Interpreting the Output
Since I added a 'name' property to the Child constructor, it would only be around if I am looking at an instance of Child, not at its .prototype.
So the first line of the Output means that the current this context is indeed the childInstance. But the second one is neither the childInstance, nor the Parent.prototype:
Call (myF of childInstance): this refers to the childInstance. Object.getPrototypeOf(this).myF(); then looks for the [[Prototype]] of the childInstance, which is the Child.prototype, not the Parent.prototype.
Output: 'did I derp??'
Call (myF of Child.prototype): this refers to the Child.prototype, which is the childInstances [[Prototype]] Property. So the second call of Object.getPrototypeOf(this).myF(); finally returns the Parent.prototype (sort of). Output: 'did I derp??'
Call (myF of Parent.prototype instance created by Object.create): Finally, the myF on the parent is called. Output: 'derp'
Since your console.log("did I derp??") comes after the myF function call, the output is in reverse order. The following graphic illustrates how the code is traversed:
So your assumption about what Object.getPrototypeOf(this).myF(); refers to, was wrong.
Solution in ES5
By #LukeP:
https://jsfiddle.net/Lpxq78bs/28/
Alternative Solution in ES6
To avoid this confusion, and since you are working with a classical inheritance pattern, you could have a look at ES6 Classes. The following would be a rough example of what you are trying to do:
class Parent {
constructor() {
}
myF() {
console.log('derp');
}
}
class Child extends Parent {
constructor() {
super();
}
myF() {
super.myF();
console.log("did I derp??");
}
}
var childInstance = new Child();
childInstance.myF();
I hope this helps in understanding what happens.
Your code is working as expected , the output you are getting is because of Object.getPrototypeOf and can be explained by
Step 1 : When you cal childInstance.myF(); then it goes to below code where this refers to childInstance itself
Child.prototype.myF = function() {
Object.getPrototypeOf(this).myF();
console.log("did I derp??");
};
then Object.getPrototypeOf returns childInstance.[[Prototype]] which is Child.prototype and again call myF method(leaving second line to printed later after the execution of the method) but next time this will reference to childInstance.[[Prototype]].
Step 2 : In this call this points to childInstance.[[Prototype]]( or Child.prototype object itself)
Child.prototype.myF = function() {
Object.getPrototypeOf(this).myF();
console.log("did I derp??");
};
Now Object.getPrototypeOf returns childInstance.[[Prototype]].[[Prototype]]( which is Child.prototype.[[Prototype]]) which is Parent.prototype and again call myF method but this time myF method will print derp because myF method of Parent.prototype is being called. After that, second line will print did i derp.
Step 3 : Then the function comes back to step 1 to execute second line which again prints did i derp
If you have to work with inheritance in ES5 I have made a wrapper that makes it easy to extend and call parent methods. No frameworks required.
fiddle to working code here: https://jsfiddle.net/wcrwLmrk/13/
Here is how the code works:
/* extend the base class to the new parent class and pass
an object with the new properties and methods */
var ParentClass = Class.extend(
{
// reset the constructor to the correct constructor
constructor: function()
{
},
callName: function(arg)
{
console.log('parent ' + arg);
}
});
/* extend the parent class to the new child class and pass
an object with the new properties and methods */
var ChildClass = ParentClass.extend(
{
// reset the constructor to the correct constructor
constructor: function()
{
ParentClass.call(this);
},
callName: function(arg)
{
// child method code
console.log('child ' + arg);
/* call parent method by passing the method name and any params */
this.super('callName', arg);
}
});
Now we can create a new child class that will
call the super class method:
var child = new ChildClass();
child.callName('name');
Here is the base class that needs to be included in the project:
var Class = function()
{
};
Class.prototype =
{
constructor: Class,
/* this is an alias for callParent. this will
allow child classes to call super methods.
#param (string) method name
#param [(mixed)] addasmany args as the super
method needs
#return (mixed) the super method return value */
super: function()
{
var parent = this.parent;
if(parent)
{
var args = [].slice.call(arguments),
// this will remove the first arg as the method
method = args.shift();
if(method)
{
var func = parent[method];
if(typeof func === 'function')
{
return func.apply(this, args);
}
}
}
return false;
}
};
/* this will return a new object and extend it if an object it supplied.
#param [(object)] object = the extending object
#return (object) this will return a new object with the
inherited object */
var createObject = function(object)
{
if(!Object.create)
{
var obj = function(){};
obj.prototype = object;
return new obj();
}
else
{
return Object.create(object);
}
};
/* this will extend an object and return the extedned
object or false.
#param (object) sourceObj = the original object
#param (object) targetObj = the target object */
var extendObject = function(sourceObj, targetObj)
{
if(typeof sourceObj !== 'undefined' && typeof targetObj !== 'undefined')
{
for(var property in sourceObj)
{
if(sourceObj.hasOwnProperty(property) && typeof targetObj[property] === 'undefined')
{
targetObj[property] = sourceObj[property];
}
}
return targetObj;
}
return false;
};
var extendClass = function(sourceClass, targetClass)
{
/* if we are using a class constructor function
we want to get the class prototype object */
var source = (typeof sourceClass === 'function')? sourceClass.prototype : sourceClass,
target = (typeof targetClass === 'function')? targetClass.prototype : targetClass;
if(typeof source === 'object' && typeof target === 'object')
{
/* we want to create a new object and add the source
prototype to the new object */
var obj = createObject(source);
/* we need to add any settings from the source that
are not on the prototype */
extendObject(source, obj);
/* we want to add any additional properties from the
target class to the new object */
for(var prop in target)
{
obj[prop] = target[prop];
}
return obj;
}
return false;
};
/* this will allow the classes to be extened.
#param (object) child = the child object to extend
#return (mixed) the new child prototype or false */
Class.extend = function(child)
{
if(!child)
{
return false;
}
var parent = this.prototype;
/* the child constructor must be set to set
the parent static methods on the child */
var constructor = child && child.constructor? child.constructor : false;
if(child.hasOwnProperty('constructor') === false)
{
constructor = function()
{
var args = arguments;
parent.constructor.apply(this, args);
};
}
constructor.prototype = extendClass(parent, child);
constructor.prototype.parent = parent;
/* this will add the static methods from the parent to
the child constructor. */
extendObject(this, constructor);
return constructor;
};

Node JS: Accessing inherited function in subclass's function

Let's say I have two classes, Base and Child. Base is the base class that Child will be inheriting from. Here's the code to visualize this:
Base.js
function Base(init) {
}
function log() {
console.log('here');
}
Base.prototype.log = log;
module.exports = Base;
Child.js
var Base = require('../Base.js');
var Child = module.exports = function Child(init) {
Base.call(this, init);
};
require('util').inherits(Child, Base);
function test() {
this.log(); // doesn't work
Base.prototype.log(); // Works but is quite ugly
Child.super_.prototype.log(); // Works but is even uglier
}
Child.prototype.test = test;
What I would absolutely love to do is something like this.log() or even log() would be nice. I realize I can set a variable to that in my inherited class, but then I would have to do that for every class that inherits Base, which is definitely not ideal. So my question is, can I do something like this.log() without having to set a variable in the inherited class? Am I misunderstanding something?
Updated Answer:
From your comment below, replying to my statment that this.log() should work:
Well, so that's the thing. When I'm in Child's test function, this is an empty object, so I'm assuming somewhere down the line I'm not getting the proper scope.
You haven't shown how you're calling test, but I suspect that's where the problem is. Provided you call it via a Child instance:
var c = new Child();
c.test();
...then within the call, this will be the child instance, which will inherit (indirectly) the Parent.prototype object with its log property.
But how you call it is important. This wouldn't work, for instance:
var c = new Child();
var f = c.test;
f();
If you do that, within the call to the function, this will be the global object (or undefined if you're in strict mode), not a Child instance. This is because in JavaScript, this is set primarily by how a function is called, and calling it like that doesn't set this to what you want.
This matters for callbacks, because passing in c.test as a callback:
someFunctionThatUsesACallback(c.test);
...means the code calling back won't set this for you.
If you need to do that, Function#bind will help:
var f = c.test.bind(c); // Returns a version of c.test that, when called,
// will have `this` set to `c`
f(); // Works, `this` is the `Child` instance
And similarly:
someFunctionThatUsesACallback(c.test.bind(c));
More (on my blog):
Mythical methods
You must remember this
Original Answer:
If you set up the prototype hierarchy correctly, and Child.prototype doesn't have log on it (and you don't put a log property on instances), then you should be able to use this.log(); just fine. If you can't, then the hierarchy hasn't been set up correctly.
I don't know what util.inherits does, but setting up the relationship between Child and Parent correctly isn't complicated:
function Parent() {
}
Parent.prototype.log = function() {
console.log("log called");
};
function Child () {
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // This line is largely optional, but a good idea
// Usage
var c = new Child();
c.log(); // "log called"
But if you override log in your Child.prototype or assign a log property to instances, and you want to use Parent's version of log, then of course you can't just use this.log() because the property doesn't refer to Parent.prototype.log anymore.
When you need to call the parent version of something (I call them "supercalls," and I don't think that's original), you have to do more work:
I usually set up hierarchies like this by passing the parent constructor into a function I use to build the child, e.g.:
var Child = (function(Super) {
var pp = Super.prototype;
function Child() {
}
Child.prototype = Object.create(pp);
Child.prototype.doSomething = function() {
// Call `log` with appropriate `this`
pp.log.call(this);
};
return Child;
})(Parent);
By always using that pattern, I avoid having to write Parent inside the Child code (I use the Super arg instead), so if I need to rebase Child, I just change what I pass into the function.
Because that's fairly ugly (for instance, it's unclear at the top of Child that it derives from Parent, since Parent is at the bottom) and involves boilerplate code I don't feel the need to write again every time, I wrote a simple helper script for it I call Lineage, which makes it look like this:
var Child = Lineage.define(Parent, function(p, pp) {
p.doSomething = function() {
// Call `log` with appropriate `this`
pp.log.call(this);
};
});
Note that Lineage passes in both the Child and Parent prototypes as arguments, making it concise to use them (and since you get to pick those argumetn names, you can use whatever terminology works for you — I use p for the prototype of the "class" being created [Child in the above], and pp for the parent's prototype, etc.).
The standard inherits function from node.js is (in my humble opinion) very bad code. Instead I prefer to use augment to create classes:
// base.js
var augment = require("augment");
var Base = module.exports = augment(Object, function () {
this.constructor = function (init) {
};
this.log = function () {
console.log("here");
};
});
// child.js
var augment = require("augment");
var Base = require("./base");
var Child = module.exports = augment(Base, function (base) {
this.constructor = function (init) {
base.constructor.call(this, init);
};
this.test = function () {
this.log();
};
});
In addition augment.js is just 20 lines of code and can be used everywhere.
Just as an FYI, I ended up putting this in the global variable that Node creates for you. I realize that's bad practice, but it's a logging mechanism that needs to be used by any class, controller, etc., so I don't think it's that terrible of a solution.
However, in Compound, you can create no_eval controllers, which means they look like typical prototypical functions... so you can essentially create a mixin, or I can require my mixin and use it like a class... like this:
var ControllerMixin = require(process.cwd() + 'app/mixins/ControllerMixin.js');
var Log;
var LoggerController = module.exports = function LoggerController(init) {
ControllerMixin.call(this, init); // mixin approach
Log = require(process.cwd() + 'app/utils/LoggerMixin.js')(init); // class approach
};
LoggerController.prototype.index = function index(controller) {
controller.logMessage('blah'); // using mixin
Log.logError('hi'); // using class
global.logWarning('yep'); // global approach
return controller.send({success: true});
};
So there are options... just have to find what you think is the best approach.
Every answer I see online either looks complicated, or relies on external libraries. Why not just boil down to the basics, assuming you use a custom type design pattern, which is very similar to traditional OOP.
parent.js
//the main parent class
// class Parent
module.exports = Parent;
function Parent(a) {
if (!(this instanceof Parent)) {
return new Parent(a);
}
this.a = a; //Some parent variable
}
Parent.prototype = {
// Instantiate child:
getChild: function() {
var Child = require('./child');
return new Child(this);
},
// Some parent function, print some text:
printText: function(text) {
console.log(text);
}
};
child.js
//Similar to class Child extends Parent
module.exports = Child;
function Child(parent) {
this.parent = parent;
}
Child.prototype = {
// Prints Parent Variable:
printParentVariable: function() {
console.log(this.parent.a);
},
// Calls Parent Function:
callParentFunction: function() {
this.parent.printText('Child calling parent function.');
}
};
test.js
var parent = require('./parent')('parent text'); //instantiate parent with some text
var child = parent.getChild(); //create instance of a child
//*** Child has full access to its parents variables and methods ***//
console.log(child.parent.a); //Print the parent text "parent text"
child.printParentVariable(); //Child method which prints the parent variable "parent text", identical to line above.
child.parent.printText('Child calling parent'); //Call parent method, to print provided text
child.callParentFunction(); //Calls parent method, identical to above.

How to overload a parent's method in a child class in Javascript?

I'm trying to write a javascript class which extends from a parent class, overloads one method and changes it slightly.
E.g it checks some variables, if they are set to true, then it executes the same method on parent, otherwise it executes some different code.
This is what I've come up with:
function Dad(name)
{
this.yell = function()
{
console.log( 'GRRRRRRR ' + name);
}
}
function Kid(name, age)
{
var parent = new Dad(name);
parent.yell = function()
{
if (age < 15)
console.log( 'BAAAAA ' + name );
else
parent.yell(); //This is the problem line, how to call this method on
//parent object
}
return parent;
}
var k = new Kid('bob', 13);
k.yell();
However the issue is, how to call the method on the parent object.
Any ideas?
Use prototypes. They allow you to access the methods of the superclass, but without instantiating it.
Then, from the child class, you can do SuperClass.prototype.instanceMethod.call(this), which is basically super in most typical OO languages, but JS doesn't help you figure out what the superclass is. So you have to keep track of it yourself.
// Superclass
function Dad() {};
Dad.prototype.yell = function() {
console.log("Do your homework!");
}
// Subclass
function Kid(age) {
// calls the constructor of the superclass.
// in this case, the Dad() constructor does nothing, so it's not required here.
Dad.call(this);
// save constructor argument into this instance.
this.age = age;
};
// Inheritance happens here, prototype is an instance of superclass
Kid.prototype = new Dad();
// Make sure the constructor is properly assigned.
Kid.prototype.constructor = Kid;
// Override an instance method.
Kid.prototype.yell = function() {
if (this.age < 18) {
console.log('Waaaaa, I hate homework');
} else {
// calls the yell method of the superclass
Dad.prototype.yell.call(this);
}
}
// make a kid.
var k = new Kid(13);
k.yell(); // 'Waaaaa, I hate homework'
// make an old kid.
var k = new Kid(30);
k.yell(); // 'Do your homework!'
OO inheritance in JS can be messy, but there is some things out there to help.
Object.create
Resig's Simple javaScript Inheritance
Coffeescript classes
To name a few.

use the JavaScript new keyword with variable length arguments array

I am building a function that allows an object to be extended by any other object
Object.prototype.extend = function(constructor, args) {
var proto = this;
while(proto.__proto__.constructor !== Object) {
proto = proto.__proto__
}
proto.__proto__ = new constructor(args)
console.log(this);
}
the method would be called like this:
function ChildModelConstructor(1,2,3) {
this.extend(ParentModel, arguments)
}
or
instanceOfChildModel.extend(ParentModel, [1,2,3])
the problem is if I call new like this:
new constructor(args)
the constructor of the parent object receives argument which is an arguments object or array.
What I would like is to be able to call
new constructor.apply(args)
or something similar, I am not trying to change the context of this new, apply is the only method of calling a method using an args object or an array that I am aware of.
Thanks for the help :)
Update, I found a better way
Here's a better approach to Inheritance I came up with, it avoids using the depreciated proto
There are several advantages to this method, over other inheritance schemes I've found. The biggest is that it does not merge multiple levels of the proto chain. Many schemes mix the childClass's proto methods with the parent classes instance variables, or worse, all methods and properties from the parents initialization directly into the main body of the childClass.
The drawbacks are, it is single inheritance, and you cannot change the inheritance of a single instance, since the prototype property belongs to the Constructor.
Function.prototype.inherit = function(parentClass) {
var newPrototype = Object.create(Object.create(parentClass.prototype));
for(key in this.prototype){
newPrototype[key] = this.prototype[key];
}
this.prototype = newPrototype;
this.prototype.constructor = this;
this.prototype.parentClass = parentClass;
this.prototype.initParent = function(args) {
var proto = Object.getPrototypeOf(Object.getPrototypeOf(this))
this.parentClass.apply(proto, args);
}
this.prototype.uber = function() {
return Object.getPrototypeOf(Object.getPrototypeOf(this));
}
}
and you can set up the inheritance like this:
function Model(n) {
this.initParent(arguments)
this.test = n*2;
}
Model.inherit(BaseClass);
Here is a slightly more detailed version in JSFiddle http://jsfiddle.net/michaelghayes/2rHgK/​​
This is untested, but I think it will work. Replace:
proto.__proto__ = new constructor(args)
With:
proto.__proto__ = {};
proto.__proto__.prototype = constructor.prototype;
constructor.apply(proto.__proto__, args);
Take note that __proto__ is deprecated.
its better not to attach things to the object prototype and just set up the inheritance manually:
Model function() {
//init parent first because of chromes hidden classes
ParentClass.apply(this, [].slice.call(arguments))
//new instance properties
this.something = 'something'
}
Model.prototype = Object.create(ParentClass.prototype, {
constructor: {value: Model}
})
//Prototype props
Model.prototype.whatever = function(){return 'whatever'}
this also allows you to modify args before initing the parent since your new class shouldn't be restricted to using the exact same args as its parent

Defining a jQuery ajax callback parameter as an existing object type

I admit this question is getting to the limits of what I know of JavaScript & jQuery, and there is probably a more proper way to state my question (which would help in finding an existing solution), but if you can bear with me, this is what I'm after.
I have an existing object class I've defined. I'm making a jQuery ajax call using getJSON, and I want my callback parameter (which is an object) to be classed as my custom object, so that I can access that class' methods from it.
So I have some object class
function Boo() {
this.param1;
this.param2;
this.yah = function() {
...
}
}
and then I have something elsewhere of the sort
$.getJSON(url,function(new_instance) {
//from my php source this passed object is already loaded with param1, param2...
alert(new_instance.param1); //no probs
//but i want to be able to then call
new_instance.yah();
});
In other words, I want new_instance to be considered an instance of Boo(). I know in stuff like ActionScript you have to class the incoming parameters for exactly this reason, dunno what flexibility I have in JS.
I thought maybe about having an intermediate function that takes in the incoming object and creates/populates a new instance of Boo() but not sure if there is a more clever method.
Many thanks!!
Do not define methods in the constructor function, you are
defining them over and over again every time the costructor
is called. Move them over to the prototype:
Boo.prototype = {
yah: function() {
},
bah: function() {
}
...
};
a little helper function:
function coerceTo( proto, values ) {
var r = Object.create( proto );
for( var key in values ) {
r[key] = values[key];
}
return r;
}
Depending on browser, Object.create might not be available, so:
if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
}
function F() {}
F.prototype = o;
return new F();
};
}
Usage:
new_instance = coerceTo( Boo.prototype, new_instance );
new_instance instanceof Boo //true
new_instance.yah();
What you can do:
$.getJSON(url,function(newObjData) {
var newObj = $.extend(new Boo(), newObjData);
newObj.yah();
});
Also consider moving your Boo methods to object prototype so the methods don't get recreated for each Boo instance:
var Boo = function() {
this.param1;
this.param2;
}
Boo.prototype.yah = function() {
console.log(this.param1);
}

Categories