javascript关键字_让我们揭开JavaScript的“ new”关键字的神秘面纱

javascript关键字

by Cynthia Lee

辛西娅·李(Cynthia Lee)

让我们揭开JavaScript的“ new”关键字的神秘面纱 (Let’s demystify JavaScript’s ‘new’ keyword)

Over the weekend, I completed Will Sentance’s JavaScript: The Hard Parts. It might not sound like the most glorious way to spend a weekend, but I actually found it pretty fun and relaxing to complete the course. It touched on functional programming, higher-order functions, closures, and asynchronous JavaScript.

上周末,我完成了Will Sentance的JavaScript:The Hard Parts 。 听起来可能不是周末度过的最光荣的方式,但实际上,我觉得这很有趣且轻松,可以完成课程。 它涉及函数式编程,高阶函数,闭包和异步JavaScript。

For me, the highlight of the course was how he expanded on the JavaScript approaches to Object-Oriented Programming (OOP) and demystified the magic behind the new operator. I now have a well-rounded understanding of what goes on under the hood when the new operator is used.

对我而言,本课程的重点是他如何扩展JavaScript面向对象编程(OOP)的方法,并揭开了操作符背后的神秘面纱。 现在,我对使用操作员时幕后情况有了全面的了解。

JavaScript中的面向对象编程 (Object-Oriented Programming in JavaScript)

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects.” Data and functions (attributes and methods) are bundled within an object.

面向对象编程(OOP)是基于“对象”概念的编程范例。 数据和功能(属性和方法)捆绑在一个对象中。

An object in JavaScript is a collection of key-value pairs. These key-value pairs are properties of the object. A property can be an array, a function, an object itself or any primitive data type such as strings or integers.

JavaScript中的对象是键值对的集合。 这些键值对是对象的属性。 属性可以是数组,函数,对象本身或任何原始数据类型,例如字符串或整数。

What techniques do we have in our JavaScript toolbox for object creation?

我们JavaScript工具箱中有哪些技术可用于对象创建?

Let’s assume that we are creating users in a game that we just designed. How would we store user details such as their names, points, and implement methods such as an increment in points? Here are two options for basic object creation.

假设我们在刚刚设计的游戏中创建用户。 我们将如何存储用户详细信息(例如他们的姓名,积分)以及实现方法(例如增加积分)? 这是用于基本对象创建的两个选项。

选项1-对象文字表示法 (Option 1 — Object Literal Notation)

let user1 = {name: "Taylor",points: 5,increment: function() {user1.points++;}
};

A JavaScript object literal is a list of name-value pairs wrapped in curly braces. In the example above, the object ‘user1’ is created, and the associated data is stored within it.

JavaScript对象文字是用花括号括起来的名称-值对的列表。 在上面的示例中,创建了对象“ user1”,并将关联的数据存储在其中。

选项2 — Object.create() (Option 2 — Object.create())

Object.create(proto, [ propertiesObject ])

Object.create(proto, [ propertiesObject ])

Object.create methods accept two arguments:

Object.create方法接受两个参数:

  1. proto: the object which should be the prototype of the newly-created object. It has to be an object or null.

    proto:应该是新创建对象的原型的对象。 它必须是一个对象或null。
  2. propertiesObject: properties of the new object. This argument is optional.

    propertiesObject:新对象的属性。 此参数是可选的。

Basically, you pass into Object.create an object that you want to inherit from, and it returns a new object that inherits from the object you passed into it.

基本上,您将传递给Object.create一个想要继承的对象,然后返回一个新对象,该对象继承Object.create递给它的对象。

let user2 = Object.create(null);user2.name = "Cam";
user2.points = 8;
user2.increment = function() {user2.points++;
}

The basic object creation options above are repetitive. It requires each one to be manually created.

上面的基本对象创建选项是重复的。 它要求每个手动创建。

How do we overcome this?

我们如何克服这个问题?

解决方案 (Solutions)

解决方案1 ​​—使用函数生成对象 (Solution 1 — Generate objects using a function)

A simple solution is to write a function to create new users.

一个简单的解决方案是编写一个函数来创建新用户。

function createUser(name, points) {let newUser = {};newUser.name = name;newUser.points = points;newUser.increment = function() {newUser.points++;};return newUser;
}

To create a user, you would now enter the information in parameters of the function.

要创建用户,您现在将在功能参数中输入信息。

let user1 = createUser("Bob", 5);
user1.increment();

However, the increment function in the example above is just a copy of the original increment function. This is not a good way to write your code, as any potential changes to the function will need to be done manually for each object.

但是,上面示例中的增量函数只是原始增量函数的副本。 这不是编写代码的好方法,因为对该功能的任何潜在更改都需要针对每个对象手动进行。

解决方案2-使用JavaScript的原型性质 (Solution 2 — Use the prototypal nature of JavaScript)

Unlike object-oriented languages such as Python and Java, JavaScript does not have classes. It uses the concept of prototypes and prototype chaining for inheritance.

与Python和Java等面向对象的语言不同,JavaScript没有类。 它使用原型和原型链的概念进行继承。

When you create a new array, you automatically have access to built-in methods such as Array.join, Array.sort, and Array.filter. This is due to the fact that array objects inherit properties from Array.prototype.

创建新数组时,可以自动访问内置方法,例如Array.joinArray.sortArray.filter 。 这是由于数组对象继承了Array.prototype的属性。

Every JavaScript function has a prototype property, which is empty by default. You can add functions to this prototype property, and in this form, it is known as a method. When an inherited function is executed, the value of this points to the inheriting object.

每个JavaScript函数都有一个prototype属性,默认情况下为空。 您可以向该原型属性添加函数,并且以这种形式将其称为方法。 当执行继承的函数时,此值指向继承的对象。

function createUser(name, points) {let newUser = Object.create(userFunction);newUser.name = name;newUser.points = points;return newUser;
}let userFunction = {increment: function() {this.points++};login: function() {console.log("Please login.")};
}let user1 = createUser("Bob", 5);
user1.increment();

When the user1 object was created, a prototype chain bond with userFunction was formed.

创建user1对象时,形成了带有userFunction的原型链键。

When user1.increment() is in the call stack, the interpreter will look for user1 in the global memory. Next, it will look for the increment function, but will not find it. The interpreter will look at the next object up the prototype chain and will find the increment function there.

user1.increment()位于调用堆栈中时,解释器将在全局内存中查找user1。 接下来,它将查找增量函数,但找不到它。 解释器将查看原型链中的下一个对象,并在其中找到增量函数。

解决方案3- 关键字和关键字 (Solution 3 — new and this keywords)

The new operator is used to create an instance of an object which has a constructor function.

new运算符用于创建具有构造函数的对象的实例。

When we call the constructor function with new, we automate the following actions:

当我们使用new调用构造函数时,我们将自动执行以下操作:

  • A new object is created

    创建一个新对象
  • It binds this to the object

    它结合this对象

  • The constructor function’s prototype object becomes the __proto__ property of the new object

    构造函数的原型对象成为新对象的__proto__属性。
  • It returns the object from the function

    它从函数返回对象

This is fantastic, because the automation results in less repetitive code!

这太棒了,因为自动化可以减少重复代码!

function User(name, points) {this.name = name; this.points = points;
}
User.prototype.increment = function(){this.points++;
}
User.prototype.login = function() {console.log(“Please login.”)
}let user1 = new User(“Dylan”, 6);
user1.increment();

By using the prototype pattern, each method and property is added directly on the object’s prototype.

通过使用原型模式,每个方法和属性都直接添加到对象的原型上。

The interpreter will go up the prototypal chain and find the increment function under the prototype property of User, which itself is also an object with the information inside it. Remember — All functions in JavaScript are also objects. Now that the interpreter has found what it needs, it can create a new local execution context to run user1.increment().

解释器将沿着原型链向上移动,并在User的prototype属性下找到增量函数,该属性本身也是一个内部包含信息的对象。 请记住,JavaScript中的所有函数也是对象 。 现在,解释器已经找到了所需的内容,它可以创建一个新的本地执行上下文来运行user1.increment()

Side note: Difference between __proto__ and prototype

旁注:__ proto__和原型之间的区别

If you are already getting confused about __proto__ and prototype, don’t worry! You are far from the only one to be confused about this.

如果您已经对__proto__和原型感到困惑,请放心! 您远非唯一对此感到困惑的人。

Prototype is a property of the constructor function that determines what will become the __proto__ property on the constructed object.

原型是构造函数的属性,该函数确定在构造对象上将成为__proto__属性的内容。

So, __proto__ is the reference created, and that reference is known as the prototype chain bond.

因此,__ proto__是创建的引用,该引用称为原型链键。

解决方案4-ES6“语法糖” (Solution 4 — ES6 ‘syntactic sugar’)

Other languages allow us to write our shared methods within the object “constructor” itself. ECMAScript6 introduced the class keyword, which allows us to write classes that resemble normal classes of other classical languages. In reality, it is syntactic sugar over JavaScript’s prototypal behavior.

其他语言允许我们在对象“构造函数”本身内编写共享方法。 ECMAScript6引入了class关键字,该关键字使我们能够编写类似于其他古典语言的普通类的类。 实际上,它是JavaScript原型行为的语法糖。

class User {constructor(name, points) {this.name = name;this.points = points;}increment () {this.points++;}login () {console.log("Please login.")}
}let user1 = new User("John", 12);
user1.increment();

In solution 3, the associated methods were precisely implemented using User.prototype.functionName. In this solution, the same results are achieved but the syntax looks cleaner.

在解决方案3中,使用User.prototype.functionName精确实现了相关方法。 在此解决方案中,可以达到相同的结果,但是语法看起来更简洁。

结论 (Conclusion)

We have now learned more about the different options we have in JavaScript to create objects. While class declarations and the new operator are relatively easy to use, it is important to understand what is automated.

现在,我们已经了解了更多有关JavaScript创建对象的不同选项的信息。 虽然声明和 操作员相对易于使用,重要的是要了解什么是自动化的。

To recap, the following actions are automated when the constructor function is called with new:

概括地说,当用new调用构造函数时,以下动作是自动的

  • A new object is created

    创建一个新对象
  • It binds this to the object

    它结合this对象

  • The constructor function’s prototype object becomes the __proto__ property of the new object

    构造函数的原型对象成为新对象的__proto__属性。
  • It returns the object from the function

    它从函数返回对象

Thanks for reading my article, and clap if you liked it! Check out my other articles like How I built my Pomodoro Clock app, and the lessons I learned along the way.

感谢您阅读我的文章,如果喜欢您也可以鼓掌! 查阅其他文章,例如“我如何构建Pomodoro Clock应用程序”,以及我在此过程中学到的课程 。

翻译自: https://www.freecodecamp.org/news/demystifying-javascripts-new-keyword-874df126184c/

javascript关键字

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394357.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

查看 rabbitmq 启动websocket 提示404_RabbitMQ在windows下安装(笔记)

先保证Java开发环境一切正常,【jdk,maven】,然后下载两个文件,1,下载OTPhttps://www.rabbitmq.com/download.html 下载地址下载RabbitMQ Downloading and Installing RabbitMQ:地址安装没有别的操作,一直下一步就好;2&…

[Leetcode] Longest Valid Parentheses

找出字串裡最長的合法括號組 簡單說&#xff0c;一樣stack搜尋合法parenth&#xff0c;把不合法的 ( & ) index 紀錄下來&#xff0c;最後算index間的差值取最大就是最長的 public class Solution{/// <summary>/// 把不合法的( )的index記下來&#xff0c;取最長的差…

leetcode35. 搜索插入位置(二分搜索)

给定一个排序数组和一个目标值&#xff0c;在数组中找到目标值&#xff0c;并返回其索引。如果目标值不存在于数组中&#xff0c;返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素。 示例 1: 输入: [1,3,5,6], 5 输出: 2 代码 class Solution {public int sear…

[deviceone开发]-do_Album的简单示例

一、简介do_Album用来打开手机系统提供的相册&#xff0c;能选择一张或多张图片返回给开发者&#xff0c;通常相册的图片比较大&#xff0c;要经过缩放。有的时候用户也需要把别的地方获取到到图片收藏到系统相册。这个示例简单展示这个组件的2个基本功能。二、效果图三、相关下…

公办低分二本_这六所公办二本高校的计算机类相关专业值得低分段考生选择

邯郸学院——计算机科学与技术近年来&#xff0c;邯郸学院着力强化“以本为本”理念,坚持“学生中心”“产出导向”原则&#xff0c;加强学科专业建设&#xff0c;获批国家级特色专业1个&#xff0c;省级重点发展学科3个&#xff0c;省级一流专业7个&#xff0c;英语等3个专业入…

用户体验改善案例_用户体验案例研究:建立更好的体验(重新设计“和平航空”网站)...

用户体验改善案例by Peace Ojemeh (Perrie)由Peace Ojemeh(Perrie) 用户体验案例研究&#xff1a;建立更好的体验(重新设计“和平航空”网站) (A UX case study: Building a better experience (Re-designing the Air Peace Airline website)) Traveling by air is always an …

[转]FFMPEG调节音频的音量大小,混音

链接&#xff1a;https://blog.csdn.net/nil_lu/article/details/52078488 转载于:https://www.cnblogs.com/zifeiy/p/10675734.html

局域网即时通讯软件_无线局域网中,安卓手机和电脑的资源如何实现互传互访?...

安卓手机和电脑之间的资源共享&#xff0c;可实现的方案有很多&#xff0c;例如&#xff1a;方案一是各种官方或第三方出品的“XX手机助手”软件。优点是直连的传输速率最高&#xff1b;缺点一是手机和电脑必须连在一起&#xff0c;相当不方便&#xff0c;缺点二是万一中途发生…

leetcode516. 最长回文子序列(动态规划)

***给定一个字符串 s &#xff0c;找到其中最长的回文子序列&#xff0c;并返回该序列的长度。***可以假设 s 的最大长度为 1000 。 示例 1: 输入: “bbbab” 输出: 4 一个可能的最长回文子序列为 “bbbb”。 解题思路 数组含义&#xff1a;dp[i][j]子串&#xff08;i&#…

Ubuntu 14.04 FTP服务器--vsftpd的安装和配置

更新源列表 打开"终端窗口"&#xff0c;输入"sudo apt-get update"-->回车-->"输入当前登录用户的管理员密码"-->回车,就可以了。如果不运行该命令&#xff0c;直接安装vsftpd,会出现"有 几个软件包无法下载&#xff0c;您可以运…

校验电话号码 手机号码正则表达式

2019独角兽企业重金招聘Python工程师标准>>> 电话号码 手机号码 等准确详细 正则表达式电话号码正则表达式 &#xff08;支持手机号码&#xff0c;3-4位区号&#xff0c;7-8位直播号码&#xff0c;1&#xff0d;4位分机号&#xff09; ((\d{11})|^((\d{7,8})|(\d{4}…

期刊投稿状态_SCI投稿全过程解析及拒稿后处理对策

之前给大家介绍了如果使用人工智能来提高SCI写作效率的神器&#xff0c;相信大家对SCI写作已经很有信心了。但有些小伙伴后台说对投稿过程很没有概念&#xff0c;不同期刊不同状态。那么今天我们就对SCI投稿过程、投稿状态做一个总结和解析以及拒稿后处理对策及接受后期相关问答…

cake php_如何(以及为什么)在Swinject中使用Cake Pattern

cake phpby Peter-John Welcome由Peter-John Welcome 如何(以及为什么)在Swinject中使用Cake Pattern (How (and why) to use the Cake Pattern with Swinject) In my previous article, I showed how we can use the Cake Pattern to do dependency injection without any li…

运用Appium 实现添加微信好友自动化

本文为原创文章&#xff0c;如需转载请注明出处. 任务&#xff1a;实现批量添加微信好友自动化。 任务分析&#xff1a;1.首先要实现添加单个好友步骤自动化。 2.实现脚本读取Excel里的值。 3.参数化好友电话号码或者昵称。 PS:代码采用POM(Page Object Model)便于后续维护 数…

pdf.js浏览中文pdf乱码的问题解决

由于项目中需要支持移动设备在线浏览pdf&#xff0c;苹果还好&#xff0c;天生支持&#xff0c;但是安卓中就不行了&#xff0c;需要第三方组件的支持。 这里就找到了pdf.js&#xff0c;由于pdf数据太多&#xff0c;开始的时候没法一一测试&#xff0c;所以随便测试打开了几篇没…

python导入sas数据集_运用import过程进行SAS数据导入完全实用教程

运用import过程进行SAS数据导入完全实用教程1 单个规范格式文件导入。对单个文件进行导入是我们遇到最多的情况&#xff0c;主要有以下几种&#xff1a;1.1 对指定分隔符(’|’&#xff0c;’’&#xff0c;’!’&#xff0c;’ab’等)数据的导入&#xff0c;这里以’!’为例de…

【效率专精系列】善用API统一描述语言提升RestAPI开发效率

团队内部RestAPI开发采用设计驱动开发的模式&#xff0c;即使用API设计文档解耦前端和后端的开发过程&#xff0c;双方只在联调与测试时耦合。在实际开发和与前端合作的过程中&#xff0c;受限于众多因素的影响&#xff0c;开发效率还有进一步提高的空间。本文的目的是优化工具…

leetcode剑指 Offer 14- I. 剪绳子(动态规划)

给你一根长度为 n 的绳子&#xff0c;请把绳子剪成整数长度的 m 段&#xff08;m、n都是整数&#xff0c;n>1并且m>1&#xff09;&#xff0c;每段绳子的长度记为 k[0],k[1]…k[m-1] 。请问 k[0]k[1]…*k[m-1] 可能的最大乘积是多少&#xff1f;例如&#xff0c;当绳子的…

数据包提取文件_航测怎样高效提取无人机POS航点数据

无限创新工作室研发的POS数据记录仪是一款采集飞控POS 数据并管理的设备&#xff0c;它将飞控 POS 点数据进行记录&#xff0c;形成单独的POS 数据记录TXT 文本&#xff0c;并独立存储于内存卡&#xff0c;可通过USB、U 盘或内存卡形式对数据进行读取。通过对相机进行拍照控制和…

点击删除表格中的行并提交到数据库

html中&#xff1a; <el-table-column prop"operation" label"操作" width"170"> <template slot-scope"scope"> <el-button size"small" type"danger" click"deleteRow(scope.$index,s…