Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

javascript - 创建一个类的实例时,如何找出传递的参数数量? [重复](How to find out the number of arguments passed when creating an instance of a class? [duplicate])

I need to make my custom error.(我需要进行自定义错误。)

If the arguments are not numbers and if the arguments alength are more or less than two, then an error occurs.(如果参数不是数字,并且参数alength大于或小于2,则会发生错误。) class Point { constructor(x, y) { this.x = x; this.y = y; this.isNum(); } isNum() { if(typeof this.x !== 'number' || typeof this.y !== 'number' ) { throw new Error('point is not a number ') } console.log(arguments.length) } } try{ let example = new Point(1,2) } catch(e){ console.error(e) } console.log(example.arguments.length) How do I know the length of the arguments?(我怎么知道参数的长度?) Is this spelling wrong?(这是拼写错误吗?) If you can show how to solve correctly?(如果可以显示如何正确解决?) I apologize if I crookedly wrote a question.(如果我歪曲了一个问题,我深表歉意。)   ask by incognita translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using arguments object(使用arguments对象)

Note: example is defined inside try with let which cant be accessed from outside of scope(注意: example是在try中定义的,其中let不能从范围外部访问) class Point { constructor(x, y) { this.x = x; this.y = y; this.arguments = arguments; this.isNum(); } isNum() { if (this.arguments.length != 2) { throw new Error('you send more arguments') } if (typeof this.x !== 'number' || typeof this.y !== 'number') { throw new Error('point is not a number ') } } } try { let example = new Point(1, 2) console.log(example.arguments.length) } catch (e) { console.error(e) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...