xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

TypeScript private field All In One

TypeScript private field All In One

https://www.typescriptlang.org/docs/handbook/classes.html#public-private-and-protected-modifiers

https://www.typescriptlang.org/docs/handbook/2/classes.html#private

TypeScript’s private

class Animal {
  private name: string;
 
  constructor(theName: string) {
    this.name = theName;
  }
}
 
new Animal("Cat").name;
// Property 'name' is private and only accessible within class 'Animal'.
"use strict";
class Animal {
    constructor(theName) {
        this.name = theName;
    }
}

ECMAScript Private Fields

#private

class Animal {
  #name: string;
  constructor(theName: string) {
    this.#name = theName;
  }
}
 
new Animal("Cat").#name;
// Property '#name' is not accessible outside class 'Animal' because it has a private identifier.

WeakMap


"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var _Animal_name;
class Animal {
    constructor(theName) {
        _Animal_name.set(this, void 0);
        __classPrivateFieldSet(this, _Animal_name, theName, "f");
    }
}
_Animal_name = new WeakMap();


ES2021

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields

https://caniuse.com/mdn-javascript_classes_private_class_fields

https://www.sitepoint.com/javascript-private-class-fields/

https://github.com/microsoft/TypeScript/issues/39066

refs

https://www.typescriptlang.org/play

http://www.imooc.com/article/315202



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-03-26 23:50  xgqfrms  阅读(46)  评论(1编辑  收藏  举报