PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] Why Field declarations have no keywords in Javascript ES6?

 July 08, 2022     class, ecmascript-6, javascript     No comments   

Issue

class MyDemo{
  let x =5;
}

We can get an error. But when we remove the let keyword, it would be correct. I want to know why this happend.


Solution

let is used to create a new standalone identifier - a variable name. Directly inside a class, assignment is using class instance field syntax to assign to a property of the instance.

That is, this

class MyDemo {
  x = 5;
}

means you can then do

const demo = new MyDemo();
console.log(demo.x); // logs 5

x is not a new identifier with a particular block scope - rather, it's a property of the object, so it wouldn't have made sense if the syntax required (or even permitted) them to be preceded by let (or const).

A property of an object, with a particular configuration (getter, setter, configurable, writable) is a pretty different concept from a standalone identifier (declared with const, let, or var). Mixing the two, like your code does, would just have been too misleading.



Answered By - CertainPerformance
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing