javascript类中的“ SyntaxError:意外标识符”

我的javascript类中有两个函数,其中一个函数在另一个函数中调用,我使用的参数与在其他编程语言中的用法相同。却把我扔了


“ SyntaxError:意外的标识符”


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');


胡说叔叔
浏览 326回答 3
3回答

当年话下

您需要在类中定义方法。您可能还想将它们定义为静态的,因为它们实际上并不依赖于任何实例状态。class IpSubnetMatch {&nbsp; &nbsp; ip2longConvert(ip) {&nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; }&nbsp; &nbsp; inSubNet(ip,subnet) {&nbsp; &nbsp; &nbsp; &nbsp; const long_ip = this.ip2longConvert(ip);&nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; }}

青春有我

JavaScript中的类实际上并没有提供其他功能,通常被描述为在原型和继承上提供“语法糖”。ES6类提供了一种更简洁,更优雅的语法。class IpSubnetMatch {&nbsp; &nbsp; constructor() {&nbsp; &nbsp; }&nbsp; &nbsp; ip2longConvert(ip) {&nbsp; &nbsp; }&nbsp; &nbsp; inSubNet(ip,subnet) {&nbsp; &nbsp; &nbsp; &nbsp;//Call methods using this keyword.&nbsp; &nbsp; &nbsp; &nbsp;this.ip2longConvert(ip);&nbsp; &nbsp;&nbsp; &nbsp; }}类方法在类语法中不使用function关键字。使用此关键字来引用方法或属性。

幕布斯7119047

关键字function是问题。从ECMA2015开始,您应该使用箭头功能。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript