gpt4 book ai didi

javascript - 如果分配给对象属性如何抛出异常?

转载 作者:行者123 更新时间:2023-11-30 15:26:30 26 4
gpt4 key购买 nike

我的演示:

let NullReferenceException = (function () {
class NullReferenceException {
constructor(message) {
let _ = {
'Message': message
};
return _;
}
}
return NullReferenceException;
}());

let string = (function () {
let _source = Symbol('string');

class string {
constructor(value) {
this[_source] = value || null;

if (value) this.Length = value.length;

// invalid syntax
this.Length = value ? value.length :

throw new
NullReferenceException('Object reference not set to an instance of an object.');
}
}
return string;
}());

用法:

try {
let s = new string(); // Don't throw exception here

// throw exception here (reason: cannot assign to "Length" property of null)
let length = s.Length;
} catch (e) {
console.log(e.Message);
}

我的目标:定义s 变量后,string 构造函数内不会抛出异常。但是,s.Length 做到了。

如果我用

if (value) this.Length = value.length;

它不会抛出任何异常。只是返回 undefined

let length = s.Length; // undefined

有没有办法实现我的目标?

最佳答案

您可以使用适当的逻辑为 Length 属性定义一个 getter,而不是尝试提前设置它:

// assuming _source has already been defined
class string {
constructor(value) {
this[_source] = value || null;
}

get Length () {
const value = this[_source];
if (value) {
return value.length;
} else {
throw new NullReferenceException('Object reference not set to an instance of an object.');
}
}
}

引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

关于javascript - 如果分配给对象属性如何抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42901464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com