JavaScript writing skills, function a call function B, how to write code in function B interrupt function a run?

Source: Internet
Author: User
Tags define array continue error handling exception handling implement return terminates
function | tips

function Funca () {
FUNCB ();
Other code
}
How to define function B so that B can not only terminate B itself while it is running, but also terminate the operation of function a?

This is an unconventional question and we discuss it in two major parts. (1. Why do you do this? 2. How to achieve)

1. Obviously, this coding method has disrupted the formal principle of programming, we write the purpose of the function is to encapsulate, in order to realize the modularization of the code. If B can get a out of the way, the encoding is more than a misuse of the goto statement.

Is this necessary? Why do you have to do this ...??

The answer is as follows:
If we want to extend the prototype of the array. For example: Define a Find method that returns the first array element that makes the function true.

1 <script>
2//by Go_rush (Asun) @ http://ashun.cnblogs.com
3
4 Array.prototype.each=function (f) {
5 for (Var i=0;i<this.length;i++) F (this[i],i,this)
6}
7
8 Array.prototype.find=function (f) {
9 var result;
This.each (function (Value,index,arr) {
One if (f (value,index,arr)) Result=value
12})
return result
14}
15
var arr=[1,2,3,4,5,7,9]
17
% function Foo (v) {//detection is not even
Return v%2==0
20}
Alert (Arr.find (foo))
22
</script>

The result is another disappointment.
First: Logically, the program is wrong, because we expect to return the first even number, but the program returns the last even number.
Second: The efficiency of the program is low, even if you find the last number, he found even 4, still detect all the elements after 4. This action
is superfluous.

What do we do?  Look at line 11th in the code, if it detects that F (Value,index,arr) is true, it would be nice to interrupt the function This.each () directly. Efficiency, results, a win-win situation.

So for the question one "why do you have to do this", here, specifically to this application, there is enough reason for function B () to break function A ()

See here, you may ask: why don't you find the way to write this?

Array.prototype.find=function (f) {
for (Var i=0;i<this.length;i++) {
if (f (this[i],i,this)) return this[i]
}
}

This is not the whole world is pure.

Yes, if I was simply writing a find this would be fine, but if I'm writing a complex application right now, or writing a JS framework,

I want to implement a series of
Array.prototype.all
Array.prototype.any
Array.prototype.each
Array.prototype.map
Array.prototype.find
Array.prototype.findAll
Array.prototype.grep
Array.prototype.inject
...... Please see Prototype.js v1.4 there are 10 ways to achieve it, how can I not use the For loop for each method
Iterate over the array. I definitely want to implement a each method as a unified entry bar.

Gossip less, we see how to solve the problem:
To terminate the A function in the B function and return the result, the only way I can think of is to use the exception Try{}catch (x) {}


Implementation code
1 <script>
2//by Go_rush (Asun) @ http://ashun.cnblogs.com
3
4 var $break =new Object ()
5
6 array.prototype.each=function (f) {
7 try{
8 for (Var i=0;i<this.length;i++) {
9 try{
Ten f (this[i],i,this)
One}catch (e) {
if (e== $break) throw E
13}
14}
}catch (e) {
16}
17}
18
Array.prototype.find=function (f) {
var result;
This.each (function (Value,index,arr) {
if (f (Value,index,arr)) {
Result=value
Throw $break
25}
26})
return result
28}
29
var arr=[1,2,3,4,5,7,9]
31
function foo (v) {//detect is not even
V%2==0 return
34}
Alert (Arr.find (foo))
36
Panax Notoginseng </script>
On line 24th, if the program has found the first element that satisfies the return value of the function, it throws a custom exception that terminates the This.each ()
Run.. Note that line 12th terminates the function by ensuring that the function throws a custom exception that continues to throw an exception up.

In the code above, the try---Catch method I used was entirely designed to solve the problem raised by this post, without any other error handling.

In this regard, prototype.js, by defining two custom exception objects $break and $continue, both take care of the exception handling, and solve the paste
Questions raised. Enumerable object to achieve a very elegant, we may wish to experience the prototype.js in the enumerable of the beauty.

Let's see how prototype.js does it, and I'll stick it out.

Prototype.js's code fragment extracts
var $break = new Object ();
var $continue = new Object ();

var enumerable = {
  each:function (iterator) {
    var index = 0;
    try {
      This._each (function (value) {
         try {
          iterator (value, index++);
        catch (E) {
          if (e!= $continue) throw e;
       }
     });
   } catch (e) {
      if (e!= $break) throw e;
   }
 },

All:function (iterator) {
var result = true;
This.each (function (value, index) {
result = Result &&!! (Iterator | | PROTOTYPE.K) (value, index);
if (!result) throw $break;
});
return result;
},

Any:function (iterator) {
var result = true;
This.each (function (value, index) {
if (result =!!) (Iterator | | PROTOTYPE.K) (value, index))
Throw $break;
});
return result;
},
Http://www.cnblogs.com/ashun/archive/2006/11/29/function_call_prototype_break_continue_gorush.html



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.