jbodily
jbodily

Reputation: 3873

new Function with Prototype

In javascript we have the following method for object creation:

// Prototype Object
var prototype = {
  jump: function() {}
}

// Create person
var person = Object.create(prototype)

My Question is this: Is there a way to do this to create new functions? In other words:

// Prototype Object
var prototype = {
  jump: function() {}
}

// Create person and somehow define invokation
var person = ?? // e.g.'Function.create(prototype, function() {})'

Obviously Function.create doesn't work. I'm wondering if there is a native way of doing this rather than creating a new function and assigning it a long list of methods. Functions are objects after all, no? If this doesn't make sense in Javascript, why not?

** Update ** For clarity's sake, let me add the following. The result of person creation should be a person function object that is invokable but also has prototypical functions, e.g. person() and person.jump();

Upvotes: 0

Views: 146

Answers (3)

Ixrec
Ixrec

Reputation: 976

Pre-Update Answer

It's not really clear in your question, but I assume what you're trying to do is create an object with a certain set of functions (as defined by the prototype) while at the same time providing implementations for one or more of those functions.

I don't know of any way to do this in a single line, but it's easy to do in two lines:

// Prototype Object
var prototype = {
  jump: function() { console.log('jump'); }
}

var person = Object.create(prototype);            // Create person
person.jump = function() { console.log('fly'); }; // then define invocation

person.jump(); // outputs 'fly'

If you're interested redefining methods on "closure classes" that have access to "private" members, I'm pretty sure there is no way to do that (if there was, those members wouldn't really be private).

Upvotes: 1

Ixrec
Ixrec

Reputation: 976

Post-Update Answer

Javascript has no preexisting built-in method that I'm aware of which does this (and I doubt anyone would want it to) but it's fairly easy to write your own:

function FunctionObjectCreate(prototype, mainFunc) {
    Object.keys(prototype).forEach(function(key) {
        mainFunc[key] = prototype[key];
    });
    return mainFunc;
}

var prototype = {
    jump: function() { console.log('jump'); }
};

var person = FunctionObjectCreate(prototype,
                                  function() { console.log('person'); });

person();      // prints 'person'
person.jump(); // prints 'jump'

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120586

f.call.bind(f, null)

should do what you want.

Upvotes: 1

Related Questions