美文网首页
Class 的基本语法

Class 的基本语法

作者: 木中木 | 来源:发表于2017-12-05 09:18 被阅读0次

传统一个函数的申明和方法建立,如下所示:

function Point(x,y){
  this.x = x;
  this.y = y ;
}
Point.prototype.toString = function(){
  return 'x:'+this.x +',y:'+this.y;
}
let point = new Point(1,3);
console.log(point.toString())

上面这种写法跟传统的面向对象语言(比如 C++ 和 Java)差异很大,很容易让新学习这门语言的程序员感到困惑。

ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。

class Point {
  // ...
}

typeof Point // "function"
Point === Point.prototype.constructor // true

上面代码表明,类的数据类型就是函数,类本身就指向构造函数

class Point {
  constructor(x,y){
    this.x = x;
    this.y = y ;
    
  }
  toString(){
    return 'x:'+this.x +',y:'+this.y;
  }
}
let point = new Point(1,3);
console.log(point.toString())

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

class Point {
  constructor(x, y) {
    // ...
  }

  toString() {
    // ...
  }
}

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

类的实例对象

class Point {
  // ...
}

// 报错
var point = Point(2, 3);

// 正确
var point = new Point(2, 3);
//定义类
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

上面代码中,x和y都是实例对象point自身的属性(因为定义在this变量上),所以hasOwnProperty方法返回true,而toString是原型对象的属性(因为定义在Point类上),所以hasOwnProperty方法返回false。这些都与 ES5 的行为保持一致。

类不存在变量提升(hoist),这一点与 ES5 完全不同。

new Foo(); // ReferenceError
class Foo {}

私有方法是常见需求,但 ES6 不提供,只能通过变通方法模拟实现

class Widget {

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

  // 私有方法
  _bar(baz) {
    return this.snaf = baz;
  }
另一种方法就是索性将私有方法移出模块,因为模块内部的所有方法都是对外可见的。
  class Widget {
  foo (baz) {
    bar.call(this, baz);
  }

  // ...
}

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

私有属性

与私有方法一样,ES6 不支持私有属性。目前,有一个提案,为class加了私有属性。方法是在属性名之前,使用#表示。
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,这样就不会找不到print方法了。

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());

Class 的取值函数(getter)和存值函数(setter)

§

与 ES5 一样,在“类”的内部可以使用getset关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。

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'

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 classMethod() {
    return 'hello';
  }
}

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

Bar.classMethod() // "hello, too"

Class 的静态属性和实例属性

§

静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。

// 以下两种写法都无效
class Foo {
  // 写法一
  prop: 2

  // 写法二
  static prop: 2
}

Foo.prop // undefined

类的实例属性

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

class MyClass {
  myProp = 42;

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

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

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

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

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

需要注意的是,子类继承父类时,new.target会返回子类。

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

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

var obj = 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();  // 报错
var y = new Rectangle(3, 4);  // 正确

相关文章

  • 第3章 ES6类(Class)使用

    目标 Class基本语法 constructor方法 类的实例对象 1、Class基本语法js传统创建新对象的方法...

  • 第3章 ES6类(Class)使用

    目标 Class基本语法 constructor方法 类的实例对象 1、Class基本语法 js传统创建新对象的方...

  • class 基本语法

    1.简介 JavaScript 语言中,生成实例对象的传统方法是通过构造函数。下面是一个例子。 上面这种写法跟传统...

  • Class 的基本语法

    简介 严格模式 constructor 方法 类的实例对象 Class 表达式 不存在变量提升 私有方法和私有属性...

  • Class 的基本语法

    传统一个函数的申明和方法建立,如下所示: 上面这种写法跟传统的面向对象语言(比如 C++ 和 Java)差异很大,...

  • Class的基本语法

    一. 简介 1 类的由来 es5js语言中生成实例对象的方法通过 构造函数 ES6 提供了更接近传统语言的写法,引...

  • Class 的基本语法

    一、简介 JavaScript 语言的传统方法是通过构造函数定义并生成新对象。 ES6 提供了更接近传统语言的写法...

  • Class的基本语法(笔记)

    js与es6对比 1.js中没有类(class)这个概念,通过构造函数的方式实例化对象。 2.es6中,引入类这个...

  • ES6之class

    class基本语法: 1.实质: ​ class只是一个语法糖,类的所有方法都定义在类的prototype...

  • Class的基本语法和继承

    JS引擎是一个大的工厂,工厂的专家制作出了Object.prototyp产品在这个产品的基础上又制造出了Funct...

网友评论

      本文标题:Class 的基本语法

      本文链接:https://www.haomeiwen.com/subject/qfbmbxtx.html