简体   繁体   English

用Javascript定义对象方法的两种方式有什么区别?

[英]What is the difference between two ways of defining object methods in Javascript?

While reading this article https://medium.com/javascript-scene/the-single-biggest-mistake-programmers-make-every-day-62366b432308 by Eric Elliot, I came across the following type of object method definition. 在阅读Eric Elliot的这篇文章https://medium.com/javascript-scene/the-single-biggest-mistake-programmers-make-every-day-62366b432308时 ,我遇到了以下类型的对象方法定义。

 var obj = { getX() { document.write('X'); } } obj.getX(); // X 

How is it different than the following type of definition? 它与以下定义类型有何不同?

 var obj = { getX: function getX() { document.write('X'); } } obj.getX(); // X 

The first notation is ES2015/ES6 shorthand notation and will not work in safari or internet explorer 第一种表示法是ES2015 / ES6的简写表示法,不适用于Safari或Internet Explorer

docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions docs: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Method_definitions

as the first is a shorthand notation for the second, that implies that there is no difference as far as functionality goes - however, until internet explorer is dead and buried and safari catches up (or follows internet explorer to the same grave) the first notation is not recommended for public facing sites as there is no possibility of "shim" or "polyfill" for syntax changes 因为第一个是第二个的简写表示法,这意味着就功能而言并没有区别 -但是,直到Internet Explorer死掉并被埋葬并且野生动物园赶上(或跟随Internet Explorer到达同一坟墓)为止,第一个符号不建议用于面向公众的网站,因为语法更改不可能使用“ shim”或“ polyfill”

most importantly, most "native mobile" browsers do not supports this (not talking about chrome/firefox for android etc) 最重要的是,大多数“本地移动”浏览器都不支持此功能(不是在谈论chrome / firefox for android等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 这两种定义类/对象的方式有什么区别? - what's the difference between these two ways of defining a class/object? 这两种在JavaScript函数中利用arguments对象的方式有什么区别? - What is the difference between these two ways to leverage the arguments object in a JavaScript function? 对象方法可以引用对象属性的两种方式之间的区别 - Difference between the two ways object methods can reference object properties 这两种声明原型方法的方法有什么区别? - What is the difference between these two ways of declaring prototype methods? JavaScript Object创建方法有什么区别? - What is the difference between JavaScript Object creation methods? 这两种JavaScript继承方式有什么区别 - What's the difference between these two inheritance ways in JavaScript 这两种用JavaScript编写原型函数的方式有什么区别 - What's the difference between these two ways of writting a prototype function in JavaScript 这两种获取canvas对象的方式有什么区别 - What's the difference between these two ways to get the canvas object 这两种创建对象文字的不同方式有什么区别 - What is the difference between these two different ways of creating an object literal 这两种在 Javascript 对象中编写方法的方法有什么区别? - Whats the difference between these two ways to write a method in a Javascript object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM