Js 中的类

ES5中,使用构造函数是这样的:

//定义类
function Point(x, y) {
  this.x = x;
  this.y = y;
}
Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);

ES6中,构造函数

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

上面中constructor就是构造方法。
注意定义类的方法时,前面不需要加上function
构造函数的 prototype属性,在ES6中继续存在。事实上,类的所有方法都定义在prototype属性上面

class Point {
  constructor() {
    // ...
  }
  toString() {
    // ...
  }
  toValue() {
    // ...
  }
}
// 等同于
Point.prototype = {
  constructor() {},
  toString() {},
  toValue() {},
};

在类的实例上面调用方法,其实就是调用原型上的方法

class B {}
let b = new B();
b.constructor === B.prototype.constructor // true

由于类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面。Object.assign方法可以很方便地一次向类添加多个方法。

class Point {
  constructor(){
    // ...
  }
}
Object.assign(Point.prototype, {
  toString(){},
  toValue(){}
});

类的实例对象
生成类的实例对象的写法,与ES5一样,也是使用new命令

class Point {
  // ...
}
// 报错
var point = Point(2, 3);
// 正确
var point = new Point(2, 3);

与ES5一样,实例的属性除非显式定义在其本身(即定义在this对象上,否则都是定义在原型上(即定义在class上)

//定义类
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

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

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'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 什么是Class 类? MDN上说:类定义对象的特征。它是对象的属性和方法的模板定义。简单说,“类”是生产对象的模...
    饥人谷_风争阅读 898评论 0 3
  • 继承6种套餐 参照红皮书,JS继承一共6种 1.原型链继承 核心思想:子类的原型指向父类的一个实例 Son.pro...
    灯不梨喵阅读 3,243评论 1 2
  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 4,183评论 3 11
  • javascript的语言传统方法是通过构造函数,定义并生成新的对象: function point(x,y){ ...
    overflow_hidden阅读 348评论 0 0
  • 现在,已经是2016年1月, 口头说着要时刻提醒才能不出错的2016,难免有些不习惯。 很多人都说,2016不过就...
    阿又又人余阅读 296评论 0 0

友情链接更多精彩内容