Class的基本用法

Class(类)这个概念,作为对象的模板。class可以看作只是一个语法糖,通过class关键字,可以定义类。让对象原型的写法更加清晰、更像面向对象编程的语法。类和模块的内部,默认就是严格模式,所以不需要使用use strict指定运行模式。

1.constructor方法和实例对象

//定义类
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

ES6 的类,完全可以看作构造函数的另一种写法。类的数据类型就是函数,类本身就指向构造函数。使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致。类必须使用new调用,否则会报错。

class Point {
  // ...
}

typeof Point // "function"
Point === Point.prototype.constructor // true   prototype对象的constructor属性,直接指向“类”的本身,这与 ES5 的行为是一致的。

class Bar {
  doStuff() {
    console.log('stuff');
  }
}

var b = new Bar();
b.doStuff() // "stuff"

类的所有方法都定义在类的prototype属性上面。在类的实例上面调用方法,其实就是调用原型prototype对象上的方法,所以类的新方法可以添加在prototype对象上面。Object.assign方法可以很方便地一次向类添加多个方法。

class Point {
  constructor() {
  }

  toValue() {
  }
}

// 等同于

Point.prototype = {
  constructor() {},
  toValue() {},
};


Object.assign(Point.prototype, {
  toString(){},
});

类的内部所有定义的方法,都是不可枚举的。

class Point {
  constructor(x, y) {
  }

  toString() {
  }
}

Object.keys(Point.prototype)// []
Object.getOwnPropertyNames(Point.prototype)// ["constructor","toString"]


var Point = function (x, y) {
};

Point.prototype.toString = function() {
};

Object.keys(Point.prototype)// ["toString"]
Object.getOwnPropertyNames(Point.prototype)// ["constructor","toString"]

类的属性名,可以采用表达式。constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。

let methodName = 'getArea';

class Square {
  constructor(length) {
  }

  [methodName]() {
  }
}
class Point {
}

// 等同于
class Point {
  constructor() {}
}

class Foo {
  constructor() {
    return Object.create(null);
  }
}

new Foo() instanceof Foo
// false   constructor函数返回一个全新的对象,结果导致实例对象不是Foo类的实例。

与 ES5 一样,实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。此外,类的所有实例共享一个原型对象,这也意味着,可以通过实例的__proto__属性为“类”添加方法。

//定义类
class Point {

  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }

}

var point = new Point(2, 3);

point.toString() // (2, 3)

point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true


var p1 = new Point(2,3);
var p2 = new Point(3,2);

p1.__proto__ === p2.__proto__//true
//__proto__ 并不是语言本身的特性,这是各大厂商具体实现时添加的私有属性,虽然目很多浏览器的 JS 引擎中都提供了这个私有属性,但不建议在生产中使用该属性,避免对环境产生依赖。生产环境中,我们可以使用 Object.getPrototypeOf 方法来获取实例对象的原型,然后再来为原型添加方法/属性。
var p1 = new Point(2,3);
var p2 = new Point(3,2);

p1.__proto__.printName = function () { return 'Oops' };

p1.printName() // "Oops"
p2.printName() // "Oops"

var p3 = new Point(4,2);
p3.printName() // "Oops"

//在p1的原型上添加了一个printName方法,由于p1的原型就是p2的原型,因此p2也可以调用这个方法。而且,此后新建的实例p3也可以调用这个方法。这意味着,使用实例的__proto__属性改写原型,必须相当谨慎,因为这会改变“类”的原始定义,影响到所有实例。

2.Class表达式:与函数一样,类也可以使用表达式的形式定义。

//这个类的名字是MyClass而不是Me,Me只在 Class 的内部代码可用,指代当前类。如果类的内部没用到的话,可以省略Me。
const MyClass = class Me {
  getClassName() {
    return Me.name;
  }
};

let inst = new MyClass();
inst.getClassName() // Me
Me.name // ReferenceError: Me is not defined

采用 Class 表达式,可以写出立即执行的 Class。

let person = new class {
  constructor(name) {
    this.name = name;
  }

  sayName() {
    console.log(this.name);
  }
}('张三');

person.sayName(); // "张三"

3.不存在变量提升:

new Foo(); // ReferenceError  Foo类使用在前,定义在后,这样会报错,因为 ES6 不会把类的声明提升到代码头部。
class Foo {}

{
  let Foo = class {};
  class Bar extends Foo {
  }
} //因为Bar继承Foo的时候,Foo已经有定义了。

4.私有方法和私有属性

//1.在命名上加以区别
class Widget {

  // 公有方法
  foo (baz) {
    this._bar(baz);
  }

  // 私有方法
  _bar(baz) {//表示这是一个只限于内部使用的私有方法。但是,这种命名是不保险的,在类的外部,还是可以调用到这个方法。


    return this.snaf = baz;
  }

  // ...
}

//2.将私有方法移出模块
class Widget {
  foo (baz) {
    bar.call(this, baz);
  }

  // ...
}

function bar(baz) {
  return this.snaf = baz;
}

//3.利用Symbol值的唯一性,将私有方法的名字命名为一个Symbol值。
const bar = Symbol('bar');
const snaf = Symbol('snaf');

export default class myClass{

  // 公有方法
  foo(baz) {
    this[bar](baz);
  }

  // 私有方法
  [bar](baz) {
    return this[snaf] = baz;
  }

  // ...
};
//新的前缀#表示私有属性,而没有采用private关键字,是因为 JavaScript 是一门动态语言,使用独立的符号似乎是唯一的可靠方法,能够准确地区分一种属性是否为私有属性。

class Foo {
  #a;
  #b;
  #sum() { return #a + #b; }
  printSum() { console.log(#sum()); }
  constructor(a, b) { #a = a; #b = b; }
}

5.this的指向:类的方法内部如果含有this,它默认指向类的实例。

class Logger {
  printName(name = 'there') {
    this.print(`Hello ${name}`);
  }

  print(text) {
    console.log(text);
  }
}

const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined 
//printName方法中的this,默认指向Logger类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境,因为找不到print方法而导致报错。

解决this找不到的方法:1)构造方法中绑定this  2)使用箭头函数   3)使用Proxy,获取方法的时候,自动绑定this。

class Logger {
  constructor() {
    this.printName = this.printName.bind(this);
  }
}

class Logger {
  constructor() {
    this.printName = (name = 'there') => {
      this.print(`Hello ${name}`);
    };
  }
}

function selfish (target) {
  const cache = new WeakMap();
  const handler = {
    get (target, key) {
      const value = Reflect.get(target, key);
      if (typeof value !== 'function') {
        return value;
      }
      if (!cache.has(value)) {
        cache.set(value, value.bind(target));
      }
      return cache.get(value);
    }
  };
  const proxy = new Proxy(target, handler);
  return proxy;
}

const logger = selfish(new Logger());

6.class的取值函数getter和取值函数setter,存值函数和取值函数是设置在属性的 Descriptor描述 对象上的。

class MyClass {
  constructor() {
    // ...
  }
  get prop() {
    return 'getter';
  }
  set prop(value) {
    console.log('setter: '+value);
  }
}

let inst = new MyClass();

inst.prop = 123;
// setter: 123

inst.prop
// 'getter'

7.class的静态方法:类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。

class Foo {
  static classMethod() {
    return 'hello';
  }
}

Foo.classMethod() // 'hello'

var foo = new Foo();
foo.classMethod()// TypeError: foo.classMethod is not a function


//如果静态方法包含this关键字,这个this指的是类,而不是实例。静态方法可以与非静态方法重名。
class Foo {
  static bar () {
    this.baz();
  }
  static baz () {
    console.log('hello');
  }
  baz () {
    console.log('world');
  }
}

Foo.bar() // hello   静态方法bar调用了this.baz,这里的this指的是Foo类,而不是Foo的实例,等同于调用Foo.baz。

父类的静态方法,可以被子类继承,可以从super对象上调用。

class Foo {
  static classMethod() {
    return 'hello';
  }
}

class Bar extends Foo {
  static classMethod() {
    return super.classMethod() + ', too';
  }
}
Bar.classMethod() // "hello, too"

8.class的静态属性和实例属性(Class 内部只有静态方法,没有静态属性)

(1)类的实例属性:类的实例属性可以用等式,写入类的定义之中。

class MyClass {
  myProp = 42;

  constructor() {
    console.log(this.myProp); // 42
  }
}

为了可读性的目的,对于那些在constructor里面已经定义的实例属性,新写法允许直接列出。

class ReactCounter extends React.Component {
  state = {
    count: 0
  };
}

(2)类的静态属性:类的静态属性只要在上面的实例属性写法前面,加上static关键字就可以了。

class MyClass {
  static myStaticProp = 42;

  constructor() {
    console.log(MyClass.myStaticProp); // 42
  }
}

9.new.target属性:

new是从构造函数生成实例对象的命令。new.target属性一般用在构造函数之中,返回new命令作用于的那个构造函数。如果构造函数不是通过new命令调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的。

function Person(name) {
  if (new.target !== undefined) {//new.target === Person
    this.name = name;
  } else {
    throw new Error('必须使用 new 命令生成实例');
  }
}


var person = new Person('张三'); // 正确
var notAPerson = Person.call(person, '张三');  // 报错

Class 内部调用new.target,返回当前 Class。子类继承父类时,new.target会返回子类。利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。

class Rectangle {
  constructor(length, width) {
    console.log(new.target === Rectangle);
    this.length = length;
    this.width = width;
  }
}

var obj = new Rectangle(3, 4); // 输出 true

class Square extends Rectangle {
  constructor(length) {
    super(length, length);
  }
}

var obj1 = new Square(3); // 输出 false
class Shape {
  constructor() {
    if (new.target === Shape) {
      throw new Error('本类不能实例化');
    }
  }
}

class Rectangle extends Shape {
  constructor(length, width) {
    super();
    // ...
  }
}

var x = new Shape();  // 报错 Uncaught Error: 本类不能实例化
var y = new Rectangle(3, 4);  // 正确  Shape类不能被实例化,只能用于继承。注意,在函数外部,使用new.target会报错。

 

  • 7
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值