在javascript中有原始变量吗? [英] is there ever a use for primitive variables in javascript?

查看:87
本文介绍了在javascript中有原始变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常简单的问题,是否有一种情况,在javascript中使用原始数据类型更可取,我特别被原始布尔人打扰,请考虑以下代码

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 following code

var bool = new Boolean(false);
if (bool){
    alert(bool);
}

它将 alert 但是你会得到 false ,这有点令人困惑( false != falsy)。

it will alert but you will get false, which is kinda confusing (false != falsy).

那么使用原始数据类型尤其是原始布尔值是否有意义?

so is there ever a point in using primitive data-types and especially primitive booleans?

推荐答案

原始值非常有用(原始值之外:true,false,null,1,2等)。你在问题中讨论的是围绕它们的Object包装器。

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包装器,并在Object包装器上调用方法*。

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*.

示例1:字符串

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'

示例2:布尔

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());

这篇关于在javascript中有原始变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆