Javascript 如果分配给对象属性,如何引发异常?
我的演示:Javascript 如果分配给对象属性,如何引发异常?,javascript,Javascript,我的演示: let NullReferenceException = (function () { class NullReferenceException { constructor(message) { let _ = { 'Message': message }; return _; } } return NullReference
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;
它不会抛出任何异常。只返回未定义的
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.');
}
}
}
参考: