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

时间:2017-03-20 10:41:01

标签: javascript

我的演示:

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

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

1 个答案:

答案 0 :(得分:2)

您可以使用适当的逻辑为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