尽管我已经阅读了很多相关内容,但我还是无法理解原型(prototype)概念。
为什么会有String
和String.prototype
?
如果我有 "cat"
:
- 是
String
还是Object
? - 它是否继承了
String
或String.prototype
的所有属性/方法? - 为什么会有
String
和String.prototype
? - 我应该将 String 称为
String
对象并将String.prototype
称为 String 原型(prototype)吗?
请澄清这一点。
最佳答案
我回答这个问题是因为这个主题中有很多错误信息:
Is that a String or an Object?
否 "cat"
是一个原始字符串值:
typeof "cat"; // "string", a String value
"cat" instanceof String; // false
typeof new String("cat"); // "object", a String object
new String("cat") instanceof String; // true
稍后我将讨论类型和原始值。
Does it inherits all properties/methods from String or String.prototype?
好吧,当你使用 property accessor operator (点或括号符号),原始值在内部隐式转换为对象,因此 String.prototype
上的所有方法都可用,例如:
当您访问时:
"cat".chatAt(0);
在幕后 “cat”
被转换为对象:
Object("cat").chatAt(0);
这就是为什么您可以访问值的所有继承属性。
Why is there a String and String.prototype?
String
是一个构造函数,允许您创建String 对象 或进行类型转换:
var stringObj = new String("foo"); // String object
// Type conversion
var myObj = { toString: function () { return "foo!"; } };
alert(String(myObj)); // "foo!"
String.prototype
对象,是String对象实例继承的对象。
我知道这很令人困惑,我们有字符串值和字符串对象,但大多数时候您实际上只使用字符串值,现在不用担心字符串对象。
Should I call String the String object and String.prototype the String prototype?
你应该调用String
"The String
constructor" .
“字符串原型(prototype)”可以。
您应该知道“一切都不是对象”。
我们来谈谈类型,有五种language types指定:
- 字符串
- 人数
- bool 值
- 无
- 未定义
A primitive value是“直接在语言实现的最低级别表示的数据”,您可以获得的最简单的信息。
前面描述的类型的值可以是:
- Null:值
null
。 - 未定义:值
未定义
。 - Number:所有数字,如
0
、3.1416
、1000
等。还有NaN
,和Infinity
。 - bool 值:值
true
和false
。 - 字符串:每个字符串,例如
"cat"
和"bar"
。
关于javascript - Javascript 中的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4142230/