How best to determine if an argument is not sent to the JavaScript function

后端 未结 13 715
猫巷女王i
猫巷女王i 2020-11-28 00:40

I have now seen 2 methods for determining if an argument has been passed to a JavaScript function. I\'m wondering if one method is better than the other or if one is just ba

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 01:24

    Some times you may also want to check for type, specially if you are using the function as getter and setter. The following code is ES6 (will not run in EcmaScript 5 or older):

    class PrivateTest {
        constructor(aNumber) {
            let _aNumber = aNumber;
    
            //Privileged setter/getter with access to private _number:
            this.aNumber = function(value) {
                if (value !== undefined && (typeof value === typeof _aNumber)) {
                    _aNumber = value;
                }
                else {
                    return _aNumber;
                }
            }
        }
    }
    

提交回复
热议问题