开发问题整理
267字小于1分钟
2024-12-25
javascript 引入目录下全部文件
1. 使用 import.meta.glob
const modules = import.meta.glob("./modules/**/*.ts");
for (const path in modules) {
modules[path]().then((module) => {
// 处理引入的模块
console.log(module);
});
}
2. 使用 require.context
const modules = require.context("./modules", true, /\.ts$/);
modules.keys().forEach((key) => {
const module = modules(key);
// 处理引入的模块
console.log(module);
});
通过 new Function
将字符串表达式 exp
转换成函数
const exp = 'return getValue(1) - getValue(2)';
// 定义一个函数,用于获取数组中的值
const getValue = (index) => {
const array = [12, 23, 35];
return array[index];
};
function evalCell(){
return new Function('getValue', exp)(getValue);
}
console.log(evalCell());
具体例子可以看 VUE-文档计算
和 Function() 构造函数
JS继承与原型的关联
// 创建父类
function Animal(name) {
this.name = name;
}
Animal.prototype.sayHello = function() {
console.log('Hello, my name is ' + this.name);
}
// 创建子类
function Dog(name, food) {
// 改变 this 指向
Animal.call(this, name);
this.food = food;
}
// 改变原型指向, 使用 Object.create 创建是为了不影响原来的 Animal 类
Dog.prototype = Object.create(Animal.prototype)
// 改变 constructor 指向自身
Dog.prototype.constructor = Dog;
Dog.prototype.eat = function() {
console.log('I like eat' + this.food);
}
const dog = new Dog("Jhon", "beef");
dog.sayHello();
dog.eat();