Use code from another script

Discussion in 'Javascript' started by Archos, Feb 7, 2012.

  1. Archos

    Archos Guest

    I need to write code in one script and reference it from another. So
    I've tried the next code but it doesn't works like I was expecting

    // ==
    var g = {};

    (function() {
    function Test(a, b) {

    g[Test] = Test;
    // ==
    TypeError: g.M is not a function

    What's wrong?
    Archos, Feb 7, 2012
    1. Advertisements

  2. Archos

    Scott Sauyet Guest

    The line above should read either:

    | g.Test = Test;


    | g["Test"] = Test;

    The code you wrote assigned a property value of the function
    correctly, but the property name you assigned is what your
    implementation determines the string value of your `Test` function
    should be.

    But there's still something else wrong. Your function seems to be a
    constructor function (assigning properties to `this` and having an
    initial capital letter) but when you call it, you don't use `new`. As
    corrected above, the code would result in `g` having the properties
    `Test`, which points to the function, `a` with a value of 1, and `b`
    with a value of 2. Is that what you wanted? Or did you want to do
    something like

    | var something = new g.Test(1, 2);

    In this version, `something` now looks like {a: 1, b: 2}, although it
    has other properties inherited from Object as well.

    What are you trying to accomplish?

    -- Scott
    Scott Sauyet, Feb 7, 2012
    1. Advertisements

  3. Archos

    Archos Guest

    It's just what I want, thanks.
    I'm trying to simulate a library, which has constructor functions,
    with its properties and prototypes, to be used easily from another
    Archos, Feb 7, 2012
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.
Similar Threads
There are no similar threads yet.