1

I am creating a "class" in Javascript that will handle several HTML5 features (such as video playback).

This Javascript class also generates a Flash fallback in case those HTML5 features arent present in the browser.

The Flash fall back files communicate with the Javascript by calling global functions.

My question is:

How can I get the Javascript class to generate the necessary functions?


To my knowledge using a variable without defining it first using var will make that variable global - but this feels hacky and will certainly fail on strict mode.

The class itself could be bound to any variable, so trying to access functions inside the class without first knowing those variable is going to be problematic. Also I want this code to be as portable as possible.

1 Answer 1

1

EDIT: as mentionned by mccainz in the comments it's usually a better idea to use a namespace

You can use window to define global functions without bothering strict mode:

function MyClass() {
    // your constructor
    window.globalFunctions = window.globalFunctions || {};
}

MyClass.prototype.createGlobalFunctionFoo = function () {
    window.globalFunctions.foo = function () {
        // your code
    };
};

var myInstance = new MyClass();
myInstance.createGlobalFunctionFoo();

console.log(globalFunctions.foo); // your function

Of course you would need to do some checking to make sure you are not rewriting an existing function or some other edge cases, I just gave a straight answer.

Sign up to request clarification or add additional context in comments.

1 Comment

Good idea to tag a 'namespace' object to window and place all your globals there in order to limit footprint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.