javascript - Javascript 中的原型(prototype)

标签 javascript

尽管我已经阅读了很多相关内容,但我还是无法理解原型(prototype)概念。

为什么会有StringString.prototype

如果我有 "cat":

  • String 还是 Object
  • 它是否继承了 StringString.prototype 的所有属性/方法?
  • 为什么会有 StringString.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:所有数字,如03.14161000等。还有NaN,和 Infinity
  • bool 值:值 truefalse
  • 字符串:每个字符串,例如"cat""bar"

关于javascript - Javascript 中的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4142230/

相关文章:

javascript - AngularJS : ng-repeat (return single value)

javascript - 从其他页面获取 HTML 并将脚本附加到 "type=' 模块后'“它只工作一次然后停止

javascript - 多个 $(document).ready(function() 但只有最上面的几个正在触发

javascript - 使用 Typeahead.js/Bloodhound.js 在远程和本地源之间切换

javascript - 使用 useState hook 时 React 组件渲染两次

javascript - Angularjs 允许字母字符和特殊字符,但不允许数字

javascript - 从谷歌地图中删除折线

java - 为什么 Rhino 对这个 javascript 不满意?

javascript - 填写网页上的字段

javascript - 如何限制来自 WordPress 短代码的内容?