Hey everyone, this is #23 from John Resig Advanced JavaScript http://ejohn.org/apps/learn/#23, called
What happens if a function is an object property.
1) regarding vocabulary, the variable katana is the object, right? If the anonymous function is its property, then what is "use" called? I thought "use" would have also been called a property? or is "use" also an object because it contains a value, namely a function?
2). Is the purpose of the function to change isSharp: true to isSharp: false? What does !this.isSharp exactly do?
3) When it asserts !katana.isSharp, what is it actually asserting? that isSharp has now been set to "false"?
var katana = {
isSharp: true,
use: function(){
this.isSharp = !this.isSharp;
}
};
katana.use();
assert( !katana.isSharp, "Verify the value of isSharp has been changed." );
3 Answers 3
Yes,
katanais an object (created using the{ ... }notation). "use" is the name of the property of the object whose value will be the anonymous function (which is also an object).The function inverts the value of
isSharp(so fromtruetofalseorfalsetotrue).It is asserting that
isSharpis something which does not evaluate to true (this is nearly everything exceptundefined,null,false,0, etc). In this case, sinceisSharpis always eithertrueorfalse, it is asserting that it isfalse.
The main point (and cool part) of the sample is this line:
katana.use();
This first fetches the value of the "use" property from the katana object (that's the katana.use part). The value is the anonymous function from before. Then, that function is executed (that's the () part). The really cool part is that it is executed on behalf of the katana object -- that means this in the anonymous function is a reference to the katana object when it's called that way.
4 Comments
true". It makes sense if you define true as "something which is not false" :-) I'll make it less ambiguous, thanks for pointing that outapply. (Admittedly, most of Javascript OOP is done this way, but I still marvel at it.) There's no practical advantage, just some nice syntactic sugar which also makes it "just work" in most cases even if you don't realize what's going on1) Katana is an object. Katana.use is a function. Its a property that contains a function as value. The value it contains happens to be an anonymous function.
The distinction is that Katana.use is a property of Katana and that the value of Katana.use is a function. use is a key defined on Katana since Katana["use"] also works.
2) It's setting isSharp to NOT isSharp so either true -> false or false -> true
3) the assert is saying katana.isSharp === false which it should be since it was orginally true but then set to false.
Comments
useis a property of the objectkatana.- !this.isSharp will negate the value of this.isSharp. Ex if isSharp is true it will return false else it return false.
- The assert checks whether the result of the boolean result is true. If the result is false then the assertion fails.