Jump to content

understanding JS (this keyword)


niche

Recommended Posts

I'm working to understand JS. I found this function that I need to understand better:

function textCounter(textField, showCountField) {    if (textField.value.length > maxAmount) {        textField.value = textField.value.substring(0, maxAmount);} else {         showCountField.value = maxAmount - textField.value.length;}}

Where does the value come from as intextField.value.length, textField.value.substring, textField.value.length?Is value a property or a method, or something else?

Link to comment
Share on other sites

OK.So, in your opinion, why does this function work as well with?if (textField.value.length > maxAmount) {}if (textField.length > maxAmount) {}if (textField.size > maxAmount) {}

Link to comment
Share on other sites

As far as I know, textField doesn't have a "length" property.textField has a size property which indicates how wide (in characters) it will appear on the page.The length you want is the string length of the value. The other properties will not give you the right results.

Link to comment
Share on other sites

I'm not trying to sharpshoot just understand.Isn't textField just an arbitrary variable name in this example?If so, would that explain why this script produces a result of: 12.

<html><body><script type="text/javascript">var txt = "Hello World!";var txt2 = txt.length;document.write(txt2);</script></body></html>

Link to comment
Share on other sites

In your original code, it looks as if the textCounter function expects a reference to a textarea or text input to be passed into the textField parameter, not just an ordinary string. That is why it has a value property.

Link to comment
Share on other sites

not just an ordinary string.
Do you mean in just within the function or in general?
Link to comment
Share on other sites

Do you mean in just within the function or in general?
within the function. If you look at it, it's purpose is to be generic in so much that you can pass any references to textAreas and the behavior will be the same. string (objects) are different than DOM Elements (objects).you could make generic functions that prototype strings if you wanted, it's entirely up to you. This function though serves a specific purpose, and expects certain types of data (in this case textAreas object references) in order to do what it's supposed to do.
Link to comment
Share on other sites

So, what I'm getting is there's really no difference between:if (textField.value.length > maxAmount) {}if (textField.length > maxAmount) {}if (textField.size > maxAmount) {}except that they're different ways of coding the same thing.Right?

Link to comment
Share on other sites

So, what I'm getting is there's really no difference between:if (textField.value.length > maxAmount) {}if (textField.length > maxAmount) {}if (textField.size > maxAmount) {}except that they're different ways of coding the same thing.Right?
nope. Kind of the opposite. Ingolme explained the differences already, so I will try and supplement. first, here is what comprises a textarea when we talk about it as an object/DOM element.http://www.w3schools.com/jsref/dom_obj_textarea.asptextField in this context is assumed to be a reference to an HTML DOM element; i.e. a textarea. Text areas have a value property. The value property contains whatever has been typed into the textarea, which is represented as a string, which can have a length >= 0. If I had a text area and type This is some text
textField.value //would equal This is some texttextField.value.length  //would equal 17

there is no length or size property of a textarea, so I believe that would be undefined if you tried to use it, or would cause a script error. To find out any other information about a textarea (or any other DOM object), and what its properties are, you can use the HTML DOM Object reference on w3schools.http://www.w3schools.com/jsref/default.asp

Link to comment
Share on other sites

Thanks for pointing me to the textarea object (I've missed it), but I was asking aboyt a var named textField.textarea isn't the same as textField is it?

Link to comment
Share on other sites

Thanks for pointing me to the textarea object (I've missed it), but I was asking aboyt a var named textField.textarea isn't the same as textField is it?
I think what you're missing is that in the context of your original post, textField is a var holding a reference to a textarea or input. textField is an argument of the function textCounter, and as such will hold any value passed to textCounter when called; i.e.
var arg1 = document.getElementById('some_textarea_element');var arg2 = document.getElementById('some_input_element');textCounter(arg1, arg2);  //textCounter references these as textField and showCounter throughout the function.

Technically you could pass anything to the function, since there is no type checking or error handling, but the function will only really work right if the elements being passed to it have a value property; which are generally associated with input elements (textarea being one of them). In this way you can use this function with any combination of input elements, over and over.Further along, The properties of a variable are determined by the contents assigned to it. if you assign it a reference to a DOM element, it will have whatever properties that element has. if you assign it a string, it will have strings methods/properties; an array it will have array methods/properties, etc.just saying

if (textField.value.length > maxAmount) {}if (textField.length > maxAmount) {}if (textField.size > maxAmount) {}

on it's own is very inconclusive. I could make my own object that has all of those if I wanted to.

var textField = {  value : "This is some text I am writing",  size : 1423453232};

would make all of those above if statements work too, but it wouldn't be anything meaningful though, unless you intended it that way.

Link to comment
Share on other sites

One more question before I summarize what I've learned.What are the references for the "this.form" in <textarea>? I haven't found their ref at w3 and don't know why they're there.As in:

<html><head><script language="javascript" type="text/javascript"> var maxAmount = 250;function textCounter(textField, showCountField) {    if (textField.value.length > maxAmount) {        textField.value = textField.value.substring(0, maxAmount);} else {         showCountField.value = maxAmount - textField.value.length;}}</script></head><body><form><textarea name="ta" rows="6" style="width:340px;" onKeyDown="textCounter(this.form.ta,this.form.countDisplay);" onKeyUp="textCounter(this.form.ta,this.form.countDisplay);"></textarea><br><input readonly type="text" name="countDisplay" size="3" maxlength="3" value="250"> Characters Remaining</form></body></html>

Link to comment
Share on other sites

this.form is an old way of referencing the parent form element of an input. Perhaps its still acceptable in some cases, but in the code you posted, it should not be used.The first argument to the function (this.form.ta) is really redundant. It passes a reference to the textarea, and since the textarea is what is triggering the event, a simple this is all that would be required.The element passed by the second argument should be accessed using an id. Either by passing the id as a string for the second argument and inside the function get the reference using getElementById, or by passing the element itself as the argument (still using getElementById, but in the function call rather than inside the function).

Link to comment
Share on other sites

is there a reference for referencing javascript function parameters from html?i.e. this was successfull:

<textarea name="ta" rows="6" style="width:340px;" onKeyDown="textCounter(this,getElementById.ta2);" onKeyUp="textCounter(this,this.form.countDisplay);"></textarea><br><input readonly id="ta2" type="text" name="countDisplay" size="3" maxlength="3" value="250"> Characters Remaining

this was unsuccessful:[

<textarea name="ta" rows="6" style="width:340px;" onKeyDown="textCounter(this,getElementById.ta2);" onKeyUp="textCounter(this,getElementById.ta2);"></textarea><br><input readonly id="ta2" type="text" name="countDisplay" size="3" maxlength="3" value="250"> Characters Remaining

How would you code for the onKeyDown/Up?

Link to comment
Share on other sites

I understand!I'm still a little fuzzy about the rules for using "this". I've googled it and search w3schools for a clear ref, but haven't found a reference that satisfies me ( at least I don't remember reading one - I've read so much today). Any clear ref for the use of this in JS?

Link to comment
Share on other sites

The term you need to be researching is "scope". The this keyword is a way to specify a certain scope, but what you really need to understand is the general concepts of functions executing in a certain scope. I can't imaging the Google results for searching for "this" being very helpful, although it's interesting that the Flying Spaghetti Monster gets the third result.http://en.wikipedia.org/wiki/Scope_(programming)

Link to comment
Share on other sites

That link makes sense to me if JS uses a static scope. What else could "this" meant , in this context, than the the first parameter of the textCounter function. Right ?

Link to comment
Share on other sites

On second thought, "this" must be referring to the <textarea> because that's where the input is coming from. without the <textarea> input there's nothing for the function to do. Plus,ShadowMage spilled the beans earlier. ShadowMage's tip-off not withstanding this analysis right now for the right reason?

Link to comment
Share on other sites

Thanks for all the work everyone's put into this topic so far.At this point, I need to confirm an understanding that I've formed based on this topic. Please confirm that the this keyword refers to the owner of of the input which in this case is HTML DOM Textarea Object. Also, would it be safe to say, that to establish ownership, I need to establish the source of an input, as in source = owner?

Link to comment
Share on other sites

this refers to the scope of whatever the code is executing is in. in this context, this referes to the input element. it just so happens to be that this.form will refer to the parent form element of the input. be aware it is situation dependent, and this can cause developers problems if they don't understand scope correctly, and as such that's why closures can be such a tricky concept to some people.

Link to comment
Share on other sites

Isn't the this keyword shorthand for an array? If so, wouldn't viewing its contents clear-up confusion?If it's an array how do I view it?

Link to comment
Share on other sites

huh? I'm not sure where you got that from, I don't think anyone's made a reference to this having to do anything else but referencing the scope of the current code block being executed. It is a keyword, but the simple shorthand for an array is just the literal form:

var myArray = [];

edit: linkyhttps://developer.mozilla.org/en/JavaScript...rs/Special/this

Link to comment
Share on other sites

Isn't the this keyword shorthand for an array? If so, wouldn't viewing its contents clear-up confusion?If it's an array how do I view it?
No. this is not "shorthand for an array". It could be an array, but it isn't always an array. Most of the time it is a DOM element or custom defined object. The value of this depends on the scope in which it's used.
document.getElementById('anElement').onclick = function() {   alert(this.value);}

In the above code, this refers to the DOM element with id of 'anElement' but in the following code:

var anObject = {   value: 'A string',   func: function() {	  alert(this.value);   }}

this refers to the 'anObject' object.Specifically, I believe this refers to the parent object in which the current code is running. So in the first example, onclick would be a function or method of the DOM element. So when this is used within that function it refers to the DOM element. The same concept applies to the second example. func is a function/method of the anObject object, and so using this in that function refers to the anObject object.

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...