I have been searching for discussions about how to specify a symbol as public or private in ECMAScript 6.
As I undertand it, a private symbol would be created using a pattern similar to the following:
var itemManager = (function() {
var items = new Symbol(/* possible string description? */);
return {
[items]: [ ],
getItems: function() {
return this[items].slice();
},
addItem: function(item) {
this[items].push(item);
}
};
})();
But how could I specify the items symbol as public? Will public symbols be possible in ES6, or will they only be private (not show up in Object.getOwnPropertyNames for example)? Additionally, will public symbols be enumerable by default (show up in Object.keys)?
Could anyone please link me to relevant information?
Neither non-private names and their semantics, nor the precise syntactic support for names in general is quite settled yet. So there is nothing to link you to just yet. The best you can get is digging for the relevant threads on es-discuss.
Related
I'm reading some Typescript code and I have a hard time understanding a line.
const symbol = Symbol.for('symbolname');
class Something {
public get [symbol]() {
return true;
}
...
}
How does exactly get work? Is symbol an argument?
Symbol
According to Developer Mozilla
Every Symbol() call is guaranteed to return a unique Symbol. Every Symbol.for("key") call will always return the same Symbol for a given value of "key". When Symbol.for("key") is called, if a Symbol with the given key can be found in the global Symbol registry, that Symbol is returned. Otherwise, a new Symbol is created, added to the global Symbol registry under the given key, and returned.
Well, to make it simple, if you're familiar with object[key] in Javascript, you can understand Symbol easily.
Occasionally, we use key in some circumstances like below
const key = "keyname"
const object = {
[key]: "value"
}
Now we simply convert it to symbol usage
const symbol = Symbol.for('symbolname');
const object = {
[symbol]: "value" //the key is presented by a symbol
}
But beyond that, one outstanding feature, which we regularly use Symbol, is
Symbol-keyed properties will be completely ignored when using JSON.stringify():
It's really good to serialize JSON data but ignore some fields in your code
If you want to have a better understanding of some Symbol features, I'd suggest you read this article
Getter (in your code it's calling get)
According to Developer Mozilla again
The get syntax binds an object property to a function that will be called when that property is looked up.
But firstly, we ask why we need it?
To demonstrate it, let me show you one of my favorite examples
class Person {
public firstName: string;
public lastName: string;
public fullName: string; //you will assign a value for `fullName` like this `${firstName} ${lastName}`?
}
That fullName assignment will be repeated multiple times ridiculously even though you assigned values for firstName and lastName
To avoid that, we'd introduce getter
class Person {
public firstName: string;
public lastName: string;
//here we go with getter!
public get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
After this, you only need to assign values for firstName and lastName. And for fullName, you just simply call person.fullName which will be populated automatically!
And the last question is "Are we able to use getter with Symbol". I'd say YES!
If you check the earlier document for the getter, you can find this part
const expr = 'foo';
const obj = {
get [expr]() { return 'bar'; }
};
console.log(obj.foo); // "bar"
Conclusion
About what you ask
const symbol = Symbol.for('symbolname');
class Something {
public get [symbol]() {
return true;
}
}
Well, I guess that developer is trying to avoid unexpected data population during JSON serialization on that getter
I am trying to implement a Binary Search Tree (Github repo).
For operations like insert(data: T), find(data: T) and remove(data: T), I saw some examples in Java that have the following signature:
class BST<T extends Comparable<? super T>> { ... }
I believe with this signature it lets us create a BST comprising of objects too as a Node. Something like this:
class Person implements Comparable<Person> {
private String name;
private Integer age;
///...
///..
#override
int compareTo(Person otherObj) {
// return 0 | -1 | 1;
}
}
I'd like to implement something similar through generics in TypeScript. Here are the problems I faced and need help with/suggestions for:
Unlike Java, JS primitive types don't have the compareTo method - hence my question - How to add methods to primitive types and share that definition across the whole project. Something with creating a namespace?
interface Number {
compareTo(o: number): number;
}
Number.prototype.compareTo = function(o: number) {
// add checks for corner cases
return this > o ? 1 : this < o ? -1 : o;
}
let a = 2;
let b = 3;
a.compareTo(b); // -1;
My first question is how to share this new prototype method throughout the project?
Alternatives Can someone please suggest some alternative which in a way builds a generic binary search tree for all types of data.
class BST <T | T extends Comparable<T>> implements Tree<T> {...}
But this gave me compilation error saying that Comparable is being used as a value when it is only a _type_ among other syntax errors.
My idea was: the T should either be a primitive type or it should of the type that is implements the Comparable<T> interface.
That declaration should have worked unless the containing file was an ES6 module, in which case you'd have to put declare global { ... } around the interface declaration. If it didn't work, what error are you getting?
The best thing might be to just have the constructor of BST take a comparator of type (x: T, y: T) => number. Then callers can use a primitive type with a comparator other than the standard ordering if they want to.
Currently i started working with JS ECMA6 for my personal web app,
but I am not sure about usage of Symbols
i.e. how can I make use of it?
I believe, they are tokens that serve as unique IDs. But I am not sure about its usage in web app development.
I am currently new to this standard, please provide your suggestions on it.
Symbols enable access control for object state. Symbols allow properties to be keyed by either string (as in ES5) or symbol. Symbols are a new primitive type. Optional description parameter used in debugging - but is not part of identity. Symbols are unique (like gensym), but not private since they are exposed via reflection features like Object.getOwnPropertySymbols.
var MyClass = (function() {
// module scoped symbol
var key = Symbol("key");
function MyClass(privateData) {
this[key] = privateData;
}
MyClass.prototype = {
doStuff: function() {
... this[key] ...
}
};
return MyClass;
})();
var c = new MyClass("hello")
c["key"] === undefined
It can be referred here.
Here are few more links with nicely explained examples.(As already mentioned in comments section.)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
http://www.2ality.com/2014/12/es6-symbols.html
Is there a shorter way to write this in c#:
if(myobject!=null){
}
In JavaScript we can do this:
if(myobject){
}
Disclaimer: I know this will match 'true' as well in JavaScript. This would only be used on variables that should be a specific type of object.
I found some similar questions, but they're asking slightly different things:
C# Shortest Way to Check for Null and Assign Another Value if Not
Best and fastest way to check if an object is null
How to determine if variable is 'undefined' or 'null'?
You can obtain the same syntax in C# via operator:
public class MyClass {
...
// True if instance is not null, false otherwise
public static implicit operator Boolean(MyClass value) {
return !Object.ReferenceEquals(null, value);
}
}
....
MyClass myobject = new MyClass();
...
if (myobject) { // <- Same as in JavaScript
...
}
C# language philosophy is quite different than that of JavaScript. C# usually forces you to be more explicit about somethings in order to prevent some common programming errors (and I'm sure this also helps simplify the compiler design & test).
If C# had allowed such an implicit conversion to boolean, you are much more likely to run into programming errors like this:
if(myobject = otherObject)
{
...
}
where you've made an assignment instead of an equality check. Normally C# prevents such mistakes (so although Dmitry's answer is clever, I'd advise against it).
used ?? Operator https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operator
var myobject = notNullValue ?? nullValue;
If you want to Throw an ArgumentNullException e.g. to check method parameters, there is a handy one-liner to do this:
_ = x ?? throw new ArgumentNullException(nameof(x));
Here, we try to assign the parameter to the discard _ operator. The ??-operator performs a nullcheck. If the variable is null, the exception is thrown.
In Visual Studio you can add a custom snippet to bind this line to the shortcut arg0. You only need to type arg0, double press the TAB key, and to type the parameter name. Implementing a null check then only takes 2 seconds.
Here is the snippet. To import it into Visual Studio, please use this guide: https://learn.microsoft.com/de-de/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2019
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Argument null check for parameters</Title>
<Shortcut>arg0</Shortcut>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[_= $param$ ?? throw new ArgumentNullException(nameof($param$));]]>
</Code>
<Declarations>
<Literal>
<ID>param</ID>
<ToolTip>Name of the parameter.</ToolTip>
<Default>x</Default>
</Literal>
</Declarations>
</Snippet>
</CodeSnippet>
You can use object class static method ReferenceEquals method to find out if the refrence is null or not
MyClass1 obj = new MyClass1();
if (object.ReferenceEquals(obj,null))
{
Console.Write("obj ref is null");
}
this is my code:
<script type="text/javascript">
var Note=function(){}
Note.prototype = {
get id()
{
if (!("_id" in this))
this._id = 0;
return this._id;
},
set id(x)
{
this._id = x;
}
}
var a=new Note()
alert(a.id)
</script>
this style is like to python ,
this is my first time to see this code ,
and can you give me more example about 'get' and 'set' in javascript .
thanks
Yes it does. This feature was added in ECMAScript 5.
PropertyAssignment:
PropertyName : AssignmentExpression
get PropertyName() { FunctionBody }
set PropertyName( PropertySetParameterList ) { FunctionBody }
Here are a few things to remember when using this syntax.
If your object literal has a value property it cannot have getter or setter and vice versa.
Your object literal cannot have more than one getter or setter with the same name.
A better way to actually use this feature is through the Object.defineProperty function.
function Person(fName, lName) {
var _name = fName + " " + lName;
Object.defineProperty(this, "name", {
configurable: false, // Immutable properties!
get: function() { return _name; }
});
}
This allows you to have nice clean objects with encapsulation.
var matt = new Person("Matt", "Richards");
console.log(matt.name); // Prints "Matt Richards"
It can in certain engines, and it's in the spec for EcmaScript 5, so it should be more widely adopted in the future. The Compatibility Table doesn't direclty address this, but it will likely follow defineProperties, which provides an API for doing the same thing. As pointed out previously, John Resig has a nice article on the new object and property APIs.
Javascript does in fact support getters and setters now. John Resig has a good blog post about them here.
John's article does a good job at mentioning several different ways of defining getters/setters on Javascript objects, but doesn't do a good job at describing when each method is applicable. I believe that is much more effectively accomplished in a more recent blog post by Robert Nyman:
Getters and setters with JavaScript
(this article also introduces the ECMAScript Standard Object.defineProperty)
Yes it can. Here is a nice post about it from John Resig, the creator of jQuery:
JavaScript Getters and Setters