数据类型如何从Object获取其属性?

时间:2014-01-19 18:27:31

标签: javascript

例如;当您在JavaScript中创建数组时,其上存在所有Object的原型属性:

console.log(typeof [].valueOf); // function

我在几个地方读过“几乎所有东西都是对象”。我知道原始数据类型的异常以及它是如何工作的。

但引用的实际含义是什么?是所有数据类型原型扩展object.prototype吗?或者他们得到一个对象包装器?

我知道有一些类似的主题,但我不会说他们会回答这个问题。

4 个答案:

答案 0 :(得分:1)

这意味着作为对象的“一切”都有一个原型/原型链,最终可以解析为“对象”。

观看/播放http://www.objectplayground.com/一段时间后你会得到它。它是进行这类对话的绝佳资源。

答案 1 :(得分:1)

您可以自己测试(使用Node REPL,但可以在FF,Chrome,IE等中使用)

> Object.prototype.test()
TypeError: Object #<Object> has no method 'test'
    at repl:1:19
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.EventEmitter.emit (events.js:98:17)
    at emitKey (readline.js:1095:12)
> Array.prototype.test()
TypeError: Object  has no method 'test'
    at repl:1:18
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.EventEmitter.emit (events.js:98:17)
    at emitKey (readline.js:1095:12)
> Object.prototype.test = function(){console.log('test');}
[Function]
> Array.prototype.test()
test
undefined
>
> Object.prototype.test()
test
undefined
> String.prototype.test()
test
undefined

如果Array原型未包含Object原型,这将无效 - JavaScript中的所有对象最终都有Object.prototype,因为它是“父”

答案 2 :(得分:1)

不要被[]的简写语法混淆。也可以使用new Array() (不推荐)创建数组,这看起来可能是更熟悉的语法(您可以使用函数构造函数来识别它)。当您使用Object.getPrototypeOf()调查数组的原型链时,总是到达Object。这证明了您的阅读材料试图制作Almost everything is an object

var arr = new Array();
var constructor = Object.getPrototypeOf(Object.getPrototypeOf(arr)).constructor;
alert(constructor);

//prints: function Object() {
//          [native code]
//        }

alert(constructor === Object.prototype.constructor);
//prints true

JS小提琴: http://jsfiddle.net/ay56U/2/

答案 3 :(得分:1)

没有“数据类型”。

  

一切都是对象。

这意味着所有东西 - 函数,数组,实例,主机api,数据结构等等 - 都是object:具有可变属性的引用值。

  

是否所有数据类型原型都扩展了object.prototype?

这不是引用的含义,但大多数标准对象确实从Object.prototype继承属性(通过原型链)。