JS 面试题: 将class转为function

 关于类-需知知识点:

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

  基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。

  2、类的所有方法都定义在类的prototype属性上面。

  3、ES6 的类,完全可以看作构造函数的另一种写法。

  1. class Point {
  2. // ...
  3. }
  4. typeof Point // "function"
  5. Point === Point.prototype.constructor // true

关于new-需知知识点:

  1、通过use strict普通调用时严格模式this指向undefined,赋值操作会报错,new调用时this指向实例对象。

var Person = function () {
  'use strict';
  try {
    this.name = 'BabyChin';
    console.log('new调用');
  } catch (e) {
    console.log('普通调用');
  }
}
var p1 = new Person(); // new调用
var p2 = Person(); // 普通调用

  2、通过instanceof普通调用时this指向全局对象new调用时this指向实例对象

var Person = function () {
  if (this instanceof Person) {
    console.log('new调用');
  } else {
    console.log('普通调用');
  }
}
var p1 = new Person(); // new调用
var p2 = Person(); // 普通调用

  3、通过constructor普通调用时constructor指向全局对象new调用时constructor指向构造函数本身

var Person = function () {
  if (this.constructor === Person) {
    console.log('new调用');
  } else {
    console.log('普通调用');
  }
}
var p1 = new Person(); // new调用
var p2 = Person(); // 普通调用

  4、通过new.target普通调用时target默认指向undefinednew调用时target指向Person的实例对象。

var Person = function () {
  if (new.target === Person) {
    console.log('new调用');
  } else {
    console.log('普通调用');
  }
}
var p1 = new Person(); // new调用
var p2 = Person(); // 普通调用

 

posted @ 2024-01-28 16:02  当下是吾  阅读(45)  评论(0编辑  收藏  举报