• 目录
  • 简介
  • 收藏

    烂尾楼

    莫导喜欢听人叫他爸爸…… 要是让莫导的广大粉丝知衣冠禽兽的莫导居然有这个癖好……   你以为会发生 粉转黑、路转喷这样的事情吗?   不,他们会说我们愿意。   爸爸爹爹皇阿玛,换着花样叫都行!   床上床下叫都没关系!

    乱码

    小说: 烂尾楼 作者:衣衫似风雪 字数:1199 更新时间:2024-03-29 17:57:54

    方法

    constructor 方法

    constructor 方法是类的默认方法,创建类的实例化对象时被调用。

    class Example{

    constructor(){

    console.log('我是constructor');

    }

    }

    new Example(); // 我是constructor

    返回对象

    class Test {

    constructor(){

    // 默认返回实例对象 this

    }

    }

    console.log(new Test() instanceof Test); // true

    class Example {

    constructor(){

    // 指定返回对象

    return new Test();

    }

    }

    console.log(new Example() instanceof Example); // false

    静态方法

    class Example{

    static sum(a, b) {

    console.log(a+b);

    }

    }

    Example.sum(1, 2); // 3

    原型方法

    class Example {

    sum(a, b) {

    console.log(a + b);

    }

    }

    let exam = new Example();

    exam.sum(1, 2); // 3

    实例方法

    class Example {

    constructor() {

    this.sum = (a, b) => {

    console.log(a + b);

    }

    }

    }

    类的实例化

    new

    class 的实例化必须通过 new 关键字。

    class Example {}

    let exam1 = Example();

    // Class constructor Example cannot be invoked without 'new'

    实例化对象

    共享原型对象

    class Example {

    constructor(a, b) {

    this.a = a;

    this.b = b;

    console.log('Example');

    }

    sum() {

    return this.a + this.b;

    }

    }

    let exam1 = new Example(2, 1);

    let exam2 = new Example(3, 1);

    // __proto__ 已废弃,不建议使用

    // console.log(exam1.__proto__ == exam2.__proto__);

    console.log(Object.getPrototypeOf(exam1) === Object.getPrototypeOf(exam2));// true

    Object.getPrototypeOf(exam1).sub = function() {

    return this.a - this.b;

    }

    console.log(exam1.sub()); // 1

    console.log(exam2.sub()); // 2

    decorator

    decorator 是一个函数,用来修改类的行为,在代码编译时产生作用。

    类修饰

    一个参数

    第一个参数 target,指向类本身。

    function testable(target) {

    target.isTestable = true;

    }

    @testable

    class Example {}

    Example.isTestable; // true

    多个参数——嵌套实现

    Email
    lovenovelapp@gmail.com
    Facebook主页
    @Lovenovel
    Twitter
    @lovenovelapp