Only allow certain types for properties

function Dude() {
    this.firstName = '';
    this.lastName = '';
};

var d = new Dude();
d.firstName = 'Ok mr';
d.firstName = 100;

How do I prevent / guard the assignment of 100 to firstName so that it will always be a string? Assigning a number, array another object should convert to a string.


Try to make the variables private and write getters and setters for them. In the setter you can check for the correct type. See this answer for checking the type.

function Dude() {
    var firstName = '';
    var lastName = '';

    this.setFirstName = function(name) {
        if(typeof name == 'string' || name instanceof String) {
            firstName = name;
        }
    }
    this.getFirstName = function() {
        return firstName;
    }
};

var d = new Dude();
d.setFirstName('Ok mr');
d.setFirstName(100);

console.log(d.getFirstName()); // returns "Ok mr"

But pay attention: When you use the value of an input element or pass the name in quotes it will be a string. No matter wether it represents a number or not.

Reference: http://javascript.crockford.com/private.html


function Dude() {
   this.firstName = '';
   this.lastName = '';

   Dude.prototype.setFirstName(name) = function() {
      if(typeof name != "string") this.firstName = name.toString();
      else this.firstName = name;
   };

   Dude.prototype.setLastName(name) = function() {
      if(typeof name != "string") this.lastName = name.toString();
      else this.lastName = name;
   };
}

var d = new Dude();
d.setFirstName("name");
d.setLastName(100);

These functions check whether the names are strings, if they aren't, the name will be converted to a string. This means it will then be assigned as string to either the firstName or lastName.

链接地址: http://www.djcxy.com/p/94992.html

上一篇: Javascript中的isNan()函数不能识别toString()

下一篇: 只允许某些类型的属性