1、ts 中 interfce 和 type 有什么不同
答:interfce
和type
都可以用来定义类型,但它们使用的时候还是有些差异的
- interface:通过继承(
extends
)进行扩展,适用于面向对象结构; - type:通过交叉类型(&)进行扩展,更适合于组合多种类型或表达式更复杂的逻辑类型。
// interface 扩展类型
interface A {
x: number;
}
interface B extends A {
y: number;
}
// type 交叉扩展类型
type AType = { x: number };
type BType = AType & { y: number };
- interface 支持声明合并,type不支持,type重复定义会报错。
interface User {
name: string;
}
interface User {
age: number;
}
// 等同于
// interface User {
// name: string;
// age: number;
// }
- type 支持定义联合类型/原始类型,interface 不支持
type Result = 'success' | 'fail';
type ID = string | number;
2、new 一个关键字的时候发生了什么?
答:new 一个关键字的时候,JS 引擎会做一下 4 件事情
- 创建一个新的空对象(newObj),这个新对象会继承 Func.prototype(原型);(也就是把新对象的
__proto__
属性指向Func函数的 prototype 属性) - 会将函数内部的
this
指向这个新对象;((这样在函数内部执行 this.xxx = xxx,也就相当于 newObj.xxx = xxx 了); - 执行函数体代码,初始化新对象;
- 返回新对象。
function myNew(constructor,...args){
// 1. 创建空对象,继承构造函数的 prototype
const obj = Object.create(constructor.prototype);
// 2. 将 this 指向这个对象,执行构造函数
const result = constructor.apply(obj, args);
// 3. 如果构造函数返回的是对象,则返回它,否则返回 obj
return typeof result === 'object' && result !== null ? result : obj;
}
// 测试
function Person(name) {
this.name = name;
}
const p = myNew(Person, '大人');
3、什么是原型、原型链?
- 原型(prototype):每一个函数(构造函数)都内置的一个属性,prototype 指向一个对象(共享方法和属性),所有通过这个构造函数生成的对象都能共享用它里面的东西。
- (
__proto__
):每个对象都有一个隐藏属性__proto__
,它指向它的“父原型” - 原型链:对象通过
__proto__
→prototype
→__proto__
→ ...一层层向上查找属性或方法的过程,直到找到为止,或者走到 null 结束。
4、JavaScript 中有几种数据类型?
答:JS 的数据类型可以分为两大类:
- 基本数据类型:
number、string、boolean、null、undefined、symbol、bigint
,存的是值的本身,不可变; - 引用数据类型:引用类型:
object、function、array、date、regexp、Map
,存的是地址/引用,可变