Ramil Shavaleev
Ramil Shavaleev

Reputation: 402

How to define the function prototype if the function is defined as an object property

I want to create an object containing various functions. How can I define functions in the prototype of a constructor function, if the constructor function is a property of an object?

I tried it like this:

var UTILS = {
    MyFuncCtor1: function () {

    },
    MyFuncCtor1.prototype.MyFunc1 : function() {

    }
}

but it does not work

Upvotes: 0

Views: 79

Answers (2)

MorKadosh
MorKadosh

Reputation: 6006

sinsc UTILS is an object, defining a "left-side" value is actually defining a property in this object. Therefor the above code has no real meaning since MyFuncCtor1.prototype.MyFunc1 is not a valid key.

Once possible proper way to do that would be:

function MyFuncCtor1() {

}

 MyFuncCtor1.prototype.MyFunc1 = function() {
    alert('MyFunc1')
};

const UTILS = {
    MyFuncCtor1: new MyFuncCtor1()
}

UTILS.MyFuncCtor1.MyFunc1()

https://jsfiddle.net/kadoshms/87qdt63e/4/

Upvotes: 2

cronide
cronide

Reputation: 162

You could do it in two steps. First you define your constructor function and append your prototype functions. The you define your object and set the constructor as a property.

function MyFuncCtor1() {
}

MyFuncCtor1.protptype.MyFunc1 = function() {
}

var UTILS = {
    MyFuncCtor1: MyFuncCtor1
}

Upvotes: 1

Related Questions