is there ever a use for primitive variables in javascript?

前端 未结 3 1105
北海茫月
北海茫月 2021-01-21 00:59

a pretty simple question, is there ever a case where using a primitive data-type is preferable in javascript, i am specifically bothered by primitive booleans, consider the foll

3条回答
  •  耶瑟儿~
    2021-01-21 01:27

    The primitive values are very useful (ex of primitive values: true, false, null, 1, 2, etc). What you are talking about in the question are the Object wrappers around them.

    Object wrappers are useful because it allows you to add functions to be called on them. One more important thing is that when you call methods on the primitive values, Object wrappers are created over them and the methods are called on the Object wrappers*.

    Example 1: String

    String.prototype.sayHello = function() {
      return this + ' says hello';
    };
    
    // calling a method on a string literal temporarily converts it to a String
    console.log('John'.sayHello()); // 'John says hello'
    

    Example 2: Boolean

    var bool = new Boolean(false);
    console.log(bool); // Boolean
    console.log(bool.toString()); // 'false'
    console.log(bool.valueOf()); // false
    
    // How you can use it:
    Boolean.prototype.toCaps = function() {
      return this.valueOf().toString().toUpperCase();
    };
    
    console.log(bool.toCaps()); // 'FALSE'
    
    // calling a method on a boolean literal temporarily converts it to a Boolean
    console.log(true.toCaps()); // 'TRUE'
    console.log((1 === 1).toCaps()); // 'TRUE'
    

    DEMO: http://jsbin.com/apeGOve/1/edit

    *) Different Object wrappers are created each time a method is called on a primitive value:

    String.prototype.getWrapper = function() { return this; };
    String.prototype.setTest = function() { this.test = 'test' };
    String.prototype.getTest = function() { return this.test; };
    
    var str = '123';
    console.log('Different wrappers each time',str.getWrapper() === str.getWrapper());
    
    var wrapper = str.getWrapper();
    wrapper.setTest();
    console.log(wrapper.getTest());
    console.log(str.getTest());
    

提交回复
热议问题