Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果分配给对象属性,如何引发异常?_Javascript - Fatal编程技术网

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.');
        }
    }
}
参考: