我最近开始学习JS,主要原因——想学习node和相关框架。 我已经开始从 freecodecamp 做一些基本教程,并引用 Mozilla MDN 中的文档。
我从 ES6 构造函数开始,但坚持了一些东西。详情如下:
class Book {
constructor(author) {
this._author = author;
}
// getter
get writer() {
return this._author;
}
// setter
set writer(updatedAuthor) {
this._author = updatedAuthor;
}
}
getter 和 setter 的调用很奇怪,来自 Java,但没关系。适应!!
const ALEPH = new Book("Paulo Coelho");
let writtenBy = ALEPH.writer;
ALEPH.writer = "So we changing Authors now !!"
上面的代码(语法)在考虑以下方面时是有意义的:
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
这个类并不是 OOP 概念中真正的类,而是一个称为构造函数的模板。
It should be noted that the class syntax is just syntax, and not a full-fledged class-based implementation of an object-oriented paradigm, unlike in languages such as Java, Python, Ruby, etc.
这是有道理的,如何调用 getter 和 setter,因为它们只不过是持有函数的对象的键/属性。
如果我的理解有误或者我需要在技术上更加正确,请纠正我
问题是,我在互联网上查看了 get
是什么?和set
关键字在内部执行。
我找到了实现以及如何使用它们,而不是它们内部所做的事情。
- 如果您可以向我推荐任何有关其内部功能的文档。
使用 Java,我可以轻松引用内部实现,或者在使用关键字的情况下,查找 Java 规范或 JVM 规范以了解幕后发生的情况。我正在为 JS 寻找类似的东西。如果能引用这样的官方文档就好了。
问题:
- get 和 set 关键字在内部是如何实现的?
- 任何关于 JS 的官方文档,就像我们针对 Python 或 Java 的文档一样。
谢谢。
最佳答案
不要被 ES6
功能(class
、extends
等...)分散注意力。在 JavaScript
中,没有什么比 class
或 基于类的继承
更好的了。它们只是原生 JavaScript 函数上的语法糖。 函数
是JavaScript中的第一个类对象。
例如,上面的 Book 类将在 ES5
中使用 babel repl 进行如下转换
"use strict";
function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } }
function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var Book = /*#__PURE__*/function () {
function Book(author) {
_classCallCheck(this, Book);
this._author = author;
} // getter
_createClass(Book, [{
key: "writer",
get: function get() {
return this._author;
} // setter
,
set: function set(updatedAuthor) {
this._author = updatedAuthor;
}
}]);
return Book;
}();
了解 get
和 set
在 ES5
中如何转换。
MDN docs足以深入了解 JavaScript
及其功能。
最后一句话:尽量避免比较Java
和JavaScript
。将其作为新的东西来学习。
关于javascript - Javascript的内部实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63424559/