静态属性与静态方法 1. 不会被类实例所拥有的属性与方法 只是类自身拥有 静态方法与普通方法重名,不会冲突 静态属性
1、静态属性的声明,应该在类外部,使用“类名.属性名”的方式声明。 2、静态方法的调用,应该直接在类上调用,而不是在类的实例上调用。
静态属性应用举例: //职业类 class Profession{ } class Character { constructor(pfs) { this.pfs = pfs; } } // 静态属性做配置 Character.config = { profession: { '咒术师': 1, '弓箭手': 2 } } // 创建类的实例 new Character(Character.config.profession['咒术师']); 静态方法应用举例 class Person { // 静态方法 static format(programmer) { programmer.haveGirlFriend = true; programmer.hair = true; } } // 程序员类 class Programmer { constructor() { this.haveGirlFriend = false; this.hair = false; } } // 将程序员类的实例转为了普通类 const programmer = new Programmer(); Person.format(programmer); console.log(programmer); 类的表达式 const Person = class P { constructor() { P.a = 1; console.log(P===Person); console.log('我是鸽手!!咕咕咕!!'); } } new Person(); // 自动执行 const Person1 = new class P { constructor() { P.a = 1; console.log('我是鸽手!!咕咕咕!!'); } }(); getter setter
ES5 getter/setter const obj = { _name: '', get name() { console.log('123'); return this._name; }, set name(val) { this._name = val; } } obj.name = 222; console.log(obj); 2. Object.defineProperty var obj = { _name: '' }; Object.defineProperty(obj, 'name', { get: function() { console.log('正在访问name'); return this._name; }, set: function(val) { console.log('正在修改name'); this._name = val; } }); obj.name = 10; console.log(obj.name); ES6写法: class Person { constructor() { this._name = ''; } get name() { console.log('正在访问name'); return `我的名字是${ this._name }`; } set name(val) { console.log('正在修改name'); this._name = val; } } const person = new Person(); person.name = '鸽王'; console.log(person.name); class AudioPlayer { constructor() { this._status = 0; this.status = 0; this.init(); } init() { const audio = new Audio(); audio.src = '....'; audio.oncanplay = () => { audio.play(); this.status = 1; } } get status() { return this._status; } set status(val) { const STATUS_MAP = { 0: '暂停', 1: '播放', 2: '加载中' }; //改变按钮中的文案 document.querySelector('#app .play-btn').innerText = STATUS_MAP[val]; this._status = val; } } const audio = new AudioPlayer(); name 类名 如果类表达式中,类是有名字的,name是类的名字;类没有名字的话,会是表达式中变量或者常量的名称 class Humen { } console.log(Humen.name);//Humen const Humen = class P{ } console.log(Humen.name);//P new.target 指向new关键字后面的类 class Car { constructor() { console.log(new.target); } } new Car(); 语法糖 function Car() { if (!(this instanceof Car)) { throw Error('必须使用new关键字调用Car'); } } new Car(); 在es5中模拟类: function Person(name, age) { this.name = name; this.age = age; } console.log(new Person('张三', 11)); function Constructor(fn, args) { // 创建的对象以fn作为原型 var _this = Object.create(fn.prototype); // 执行函数并传递参数 var res = fn.apply(_this, args); return res ? res : _this; } function Person(name, age) { this.name = name; this.age = age; } Person.prototype.say = function() { console.log('我叫' + this.name); } var person = Constructor(Person, ['张三', 12]); console.log(person); |
|