Jump to content

can't JavaScript trip like jQuery


Go to solution Solved by Adam,

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


var someElement = document.getElementById('element');
someElement.value = 'some data';
That is the vanilla JS equivilent (excluding error checking) of the jQuery code

var someElement = $('#element');
someElement.val('some data');

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

Edited by ricmetal
  • Solution

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.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.