Any examples of a non-trivial and useful example of the keyword "c"?

I still find the with keyword a little ... cryptic.

In short, with behaves as follows:

 with (obj) { // do stuff } 

This adds obj to the header of the scope chain, and then executes the block block. When the block is finished, it removes obj from the header of the scope chain.

According to the MDC , this allows you to do things like

 var a, x; var r = 10; with(Math) { a = PI * r * r; x = r * cos(PI / 2); } 

So, I can refer to the Math properties - like PI - directly, without saying Math.PI Which is good, but kind of useless.

Can anyone provide an example of an interesting use of with ?

+4
source share
6 answers

An alternative to standard closure solutions using functions inside the for loop:

 <a href="#">blah</a><br> <a href="#">blah</a><br> <a href="#">foo</a><br> <script> (function() { var anchors = document.getElementsByTagName('a'); for ( var i = anchors.length; i--; ) { var link = anchors[i]; with ({ number: i }) { link.onclick = function() { alert(number); }; } } })(); </script> 

nlogax loan for providing a solution that I pretty much ripped off: Javascript of the infamous loop problem?

Here's the standard solution:

 <script> (function() { var anchors = document.getElementsByTagName('a'); for ( var i = anchors.length; i--; ) { var link = anchors[i]; (function(i) { link.onclick = function() { alert(i) } })(i); } })(); </script> 
+5
source

It should be said here that the with statement in JavaScript is widely deprecated.

See Douglas Crockford. An expression is considered harmful .

I can’t say that this is better than him (seriously, by reference), but in short, if you do this:

 with (mySuperLongObjectReferenceThatIHateTyping) { propertyAlpha = 'a'; propertyBeta = 2; propertyGamma = false; } 

You cannot know by looking at this code if you assign values ​​to the properties of the mySuperLongObjectReferenceThatIHateTyping object or the global object (window).

Crockford recommends this:

 var o = mySuperLongObjectReferenceThatIHateTyping; o.propertyAlpha = 'a'; o.propertyBeta = 2; o.propertyGamma = false; 

This is unambiguous. Or you can even use a function to have a scope and not create another global variable:

 (function(o) { o.propertyAlpha = 'a'; o.propertyBeta = 2; o.propertyGamma = false; })(mySuperLongObjectReferenceThatIHateTyping); 
+4
source

John Resig javascript microtemplating shows an interesting use for.

+3
source

I regularly use it to add several CSS properties to a style object, e.g.

 with(document.body.style) { color = 'green'; background = 'red'; } 

In addition, I used at least once to assign object properties to local variables without having to store the reference to the object by itself.

It is also an alternative to closing when you want to take a “snapshot” of a variable's value:

 var foo = []; for(var i = 10; i--;) with({ i : i }) foo[i] = function() { document.writeln(i); }; // prints 0..9 for(var i = 0; i < foo.length; ++i) foo[i](); 

Keep in mind that with can seriously affect performance, since the prototype chain of an object added to the lexical environment must be checked first when resolving the name of any variable.

+2
source

The with statement in JS is similar to the with statement in a VB.net statement. This is just a way to avoid repetition with object properties / methods.

For example, suppose label management changes based on an event / action. That label management has properties such as FontColor, CSSClass, Visibility, etc.

Instead of writing a programmer:

 myLabel.FontColor=Color.Blue myLabel.CSSClass="SomeCSSClass" myLabel.Visiblity=True myLabel.Text = "Hello World" 

We can shorten this to:

 With myLabel .Text = "Hello World" .FontColor = Color.Blue .CssClass="SomeCSSClass" .Visibility=True End With 
+1
source

I don’t test in Javascript, I’m just beginning to understand how to think that it should be used, so my opinion should not have the same weight as a person who has experience in a particular language. I would be interested in the answers to my idea.

I experimented with a style for defining class-like objects, which depends on the Javascript operator. I submit that this is legal use.

Each class-like object in this style functions as a factory for objects that satisfy a specific purpose.

This style does not use this keyword in instance methods.

This style assumes that each object formed from one of these class objects must have a public aspect and a private aspect. A Javascript object represents each of these aspects. Owners of object references actually refer only to the public aspect. However, methods know both aspects, and I implement this with closure.

I do not pretend that this style applies to cases where we really care about runtime or memory performance. I consciously sacrifice almost every one of them for programming efficiency. I expect to find many cases where I want to program something quickly and with little chance of error, and where the requirements at run time will not be critical.

Since I am trying to use the code in a browser rather than node.js, a practical consideration of the development environment for me is that syntax errors in a large source file can be difficult to correct and fix. I contrast this problem by adding code in small increments. Therefore, I want cool objects to be able to accept the definition of an instance method at a time, rather than requiring that all method definitions appear in the same source file.

I first declare an object similar to a class without any instance methods defined in it, and I put an object of the class type in any namespace in which I program.

Then, I repeatedly call an object that resembles a class with a method called init, and each time I pass an initializer, a function that must be called during instance initialization.

In the end, when I start using the class object as a factory for its instances, whenever I request it for a new instance, it creates public and private aspects for the instance, binds the private aspect to the public, then calls all the initializers that have been defined passing them a private aspect of the new instance.

In my style, every public attribute is a method. All variables whose values ​​are not functions must live on the private side.

The only thing the initializer can do is set the variable on the private side.

Another thing an initializer can do is add a method on both the public and private sides.

The order of actions for executing initializers is an object of the class necessary for their execution in the same order in which they are defined. Therefore, each initializer can rely on the public and private aspects of the instance having attributes that were set by previous initializers. For the programmer, this creates a couple of lexical areas, since initializers are not installed by any type of conditional or dynamic code; they are installed when the source files are executed by the browser immediately after reading and analyzing it.

Now in some languages, in particular in Ruby and Self, you can write a bare identifier and interpret it as a method call for the current object. So, in Ruby, “foo” can mean “self.foo” and in Self, “foo” can mean “self foo” (the method invocation syntax differs between these languages, but to the level of detail that I speak from semantics now, " self.foo "in Ruby and" self foo "in Self are the same). This abbreviation for the existence of "I" is especially convenient for invoking private methods and instance variables. Javascript does not provide this convenience.

In the context inside the instance method, where I want to use an attribute of a private or public side for its value (pay attention, not to the left side of the task), I like the convenience of accessing the attribute by simply its name and there is no need to write “vary”. or me" . to his left to find him (I use “vars” for the private aspect and “I” for the public aspect). For this reason, I complete each initializer in a Javascript statement. This seems legal to me because in my style the population of the target is lexically established. To see the attributes, the programmer only needs to look at the initializers provided earlier in the source files, at the same class object (which itself is identified by the name in the source code, therefore, for the purposes of software development, we can consider this as a lexical entity, although neither one of the Javascript parsers does not detect this).

+1
source

All Articles