Jump to content

can't JavaScript trip like jQuery


ricmetal

Recommended Posts

hi guys

so, i thought i could do something with JavaScript like jQuery does:

 

var someElement = $('#element');

 

and then do:

 

someElement.val('some data');

 

this would target $('#element')

 

is this possible to do with plain JavaScript?

 

var someElement = someFunction.functionVariable;

 

i want to add data to the function variable through the assgined variable someElement.

how do i do this? can it be done?

 

 

thanks

Link to comment
https://forums.phpfreaks.com/topic/275714-cant-javascript-trip-like-jquery/
Share on other sites

i know jQuery is javascript.

 

maybe i explained myself wrong.

 

i want to reference a function variable the same way i referenece an element with jQuery (or JavaScript using the getElementById method) as follows:

 

var john = someFunction.someVar;

 

and have john be a reference to the someVar value

 

i just wanna do this to be easier to reference the var inside the function

 

regards

You can't access the variables within a function like that. Going with your example, someFunction in JavaScript represents a callable function. You can call it as many times as you like, but it has no state -- no "context". The variables defined within it are essentially lost after each call, except from what you return.

 

It is possible for functions to retain state after they've been called, in a sense, but you need to create a new instance of the function and store variables within the this context object. Plus the function itself never has state, it returns an instance of itself which actually contains the state.

 

For example:

function foo() {
    this.bar = 'baz';
}

var instance = new foo();

console.log(instance.bar); // outputs: baz
As you can see, new foo() returns an instance of itself we store in the instance variable, which we're then able to access the properties of.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.