从我可以从这两个来源推断:
是在javascript中,当在对象的上下文中使用原始数据类型时,它在内部转换为对象。但这只是一个临时转换,因为该对象在使用后将从内存中删除。
我的问题是使用这种方法的优势是什么?是否只是为了节省内存?还是有其他建议吗?
答案 0 :(得分:1)
这只是因为JavaScript是一种prototype-based程序语言。
基于原型的编程被视为鼓励程序员专注于某些示例的行为,后来才担心将这些对象分类为原型对象,这些对象稍后以类似于类的方式使用。因此,许多基于原型的系统鼓励在运行期间更改原型。
这决定了你可以这样做:
var str = 'foo'
str.weight // just return 'undefined'
var yes = true, no = false
yes.__proto__.length = function() { return this.toString().length; }
yes.length() // 4
no.length() // 5
var num = 10, amount = 0
num.__proto__.plus = function(num) { return this + num; }
amount.plus(num) // 10
但不幸的是,JavaScript的某些功能受到了Java的影响,例如the primitive vs. object distinction,所以你得到了这些有线的东西:
var str = 'foo'
str.weight = 42
str.weight // undefined
str = new String('foo')
str.weight = 42
str.weight // 42
1.toString() // error!
var n = 1
n.toString() // '1'
答案 1 :(得分:1)
我相信JavaScript提供的一个优势是因为你提到的很容易类型强制。
正如前面提到的一条评论,JavaScript是松散的类型;你可以声明一个变量,而不必声明它是什么类型的变量,因此不知道你在做什么。这具有简单的优点,如能够写:
var str = 'hello user #',
num = 3,
sayhello = str + num;
alert(sayhello); // alerts 'hello user #3'
请注意这里如何简单地将数字添加到字符串中,就好像它本身就是一个字符串。
因此,许多运算符和方法可能不太容易在更强类型的语言中使用。您可以在参数上使用parseInt
方法,而无需先检查或转换参数的类型:
var returnWholeNumber = function (arg) {
return parseInt(arg, 10);
},
str = '5 is the answer',
num = 8.19437;
alert(returnWholeNumber(str)); // alerts number 5
alert(returnWholeNumber(num)); // alerts number 8
通过提供临时对象包装器,JavaScript可以让您不必自己进行一些转换。它只是根据你想要做的事情提供包装,然后丢弃它。因此,与更强类型的语言相比,JavaScript可以更具动态性和表现力。
这对条件也很有用。某些值(例如0
或空字符串''
)就是所谓的 falsey 。这样你就可以对它们进行简单的布尔检查,JavaScript会将原始数据类型包装在布尔包装器中。
if (!userInput) {
alert('no input');
}
然而,类型强制可能令人困惑,需要谨慎:
alert('1' + 2 + 3); // alerts 123
alert('1' + '2' + '3'); // alerts 123
alert(1 + 2 + 3); // alerts 6
也适用于条件。检查类型时使用三等于,以避免意外强制:
var i = '3';
if (i == 3) { // type-coercing conditional; i can be a string or a number and this will be true
alert('i is 3'); // will successfully alert
}
if (i === 3) { // type-checking conditional; i has to be an actual number (and the value must be 3)
alert('i is a number 3'); // will not alert because i is a string
}