1

I have two function in my javascript class where one function is called in another function, I have use the parameter how I use in other programming language. But it is throwing me

"SyntaxError: Unexpected identifier"

class IpSubnetMatch {


 function ip2longConvert(ip)
  {
  var components;
  if(components = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
  {
    var iplong = 0;
    var power = 1;
    for(var i=4; i>=1;i--)
      {
        iplong += power * parseInt(components[i]);
        power *= 256;
      }
    return iplong;
  }
  else return -1;
}

function inSubNet(ip,subnet)
{
  var mask, base_ip;
  var long_ip = ip2longConvert(ip);
  if((mask = subnet.match(/^(.*?)\/(\d{1,2})$/)) && ((base_ip = ip2longConvert(mask[1])) >= 0))
    {
      var freedom = Math.pow(2,32 - parseInt(mask[2]));
      return(long_ip > base_ip) && (long_ip < base_ip + freedom -1);
    }
  else return false;
}
}

let user = new IpSubnetMatch();
user.inSubNet('10.1.5.5', '10.1.0.0/16');
1
  • Normally you want to leave the original code so we can understand the nature of the question when someone reads it in the future. Commented Apr 8, 2019 at 17:59

3 Answers 3

2

You need to define methods in the class. You also may want to define them as static since they really don't depend on any instance state.

class IpSubnetMatch {
    ip2longConvert(ip) {
        // ...
    }
    inSubNet(ip,subnet) {
        const long_ip = this.ip2longConvert(ip);
        // ...
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

@cyborg - I've updated to include accessing other methods of the class.
Nope, facing the same issue. I have updated question with your suggestion but getting following error "TypeError: Cannot read property 'inSubNet' of undefined
@cyborg - That is strange I ran the code you just reverted and it works. jsfiddle.net/64xz2kmg
@cyborg - I'm seeing true show up in the console and no TypeError.
Without console how should I get the output as true ?
2

Classes in JavaScript do not actually offer additional functionalities and are often described as providing "syntactical sugar" over prototypes and inheritance. ES6 Classes offer a cleaner and more elegant syntax.

class IpSubnetMatch {
    constructor() {

    }

    ip2longConvert(ip) {

    }

    inSubNet(ip,subnet) {
       //Call methods using this keyword.
       this.ip2longConvert(ip);   
    }
}

Class methods do not use the function keyword in class syntax. Use this keyword to reference methods or properties.

Comments

0

The keyword function is the problem. Since ECMA2015 you should use arrow functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.