【 在 saynothing (止语) 的大作中提到: 】
: [root]$ cat for_in.js
: var str = "hello world"; // [1] 修改为: var str = new String(); [2]处没有
: 打印任何内容
: for (var x in str) {
: console.log(x); // [2]
: }
: var base_obj = {
: "foo" : "bar",
: "bar" : "foo"
: };
: if (typeof Object.create !== 'function') {
: //Object.create = function (o) {
: // var F = function () {};
: // F.prototype = o;
: // return new F();
: //}
: }
: var derived_obj = Object.create(base_obj);
: derived_obj.xyz = function() {
: 1 + 1 == 2;
: };
: for (var x in derived_obj) {
: console.log(x); //[3]
: console.log(derived_obj.hasOwnProperty(x) ? "Own property" : "Base
: property");
: }
: -----------------------------------------------
: [1]处修改为new String(),输出没有任何显示
: [2]输出显示为: "0, 1, 2, 3, ...., 10"
: [3]输出显示为:
: xyz
: Own property
: foo
: Base property
: bar
: Base property
: 请问:
: (1) [1]处定义的为啥不是String object? 感觉是char类型数组。
literal strings are primitives (typeof str === "string")
new String() creates objects (typeof str === "object" && str instanceof String)
: (2) [1]处做修改,为何for..in不能打印出String的所有properties以及methods?
for...in iterates over all enumerable properties
: (3) 为何不鼓励用new String(), 但可以是new Constructor()? w3schools的说法
: 是:"Avoid String, Number, and Boolean objects. They complicate your code and
: slow down execution speed." 会使得写代码变复杂,还有影响执行速度。
similar to boxing in java
also primitives are immutable, objects are (by default) not; passing objects
of these is confusing
: 不明白之处,还得多多请教。
--
FROM 183.195.251.*