Use code from another script


A

Archos

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) {
this.a=a;
this.b=b;
}

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

What's wrong?
 
Ad

Advertisements

S

Scott Sauyet

Archos said:
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) {
        this.a=a;
        this.b=b;
}
g[Test] = Test; ^^^^^^^
})();

g.Test(1,2); // TypeError
[ ... ]
What's wrong?

The line above should read either:

| g.Test = Test;

or

| 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
 
Ad

Advertisements

A

Archos

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?
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
scripts.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Top