web面试题
本人是一个web前端开发工程师,主要是vue框架,整理了一些面试题,今后也会一直更新,有好题目的同学欢迎评论区分享 ;-)
web面试题专栏:点击此处
手动实现Object.create
通过Object.create,可以联想到之前讲的JS的7种继承方式之一 原型式继承。
实现
function myCreate(obj) {
function Fn() { }
Fn.prototype = obj;
return new Fn();
}
测试
var obj = { a: 1, b: 2 }
var obj1 = myCreate(obj)
console.log("obj1:", obj1);
console.log("obj1.a:", obj1.a);
var obj2 = Object.create(obj)
console.log("obj2:", obj2);
console.log("obj2.a:", obj2.a);
new操作符
- 新建一个空对象
- 将对象的原型__proto__ 指向Fn的prototype
- 运行构造函数,并且通过.call 修改函数的作用域,指向obj
- 返回构造函数生成的对象,如果不是对象,则返回obj
实现
function myNew(Fn,...args){
let obj = Object.create(null);
obj.__proto__ = Fn.prototype;
let result = Fn.call(obj,...args);
return result instanceof Object ? result : obj;
}
测试
function Fruits(name, price) {
this.name = name;
this.price = price;
this.sayName = function () {
console.log(`我是水果:${this.name}`);
};
this.sayPrice = function () {
console.log(`${this.name}的价格:${this.price}...`);
};
return {
sayName: () => {
console.log(`我是水果:${this.name}`);
},
sayPrice: () => {
console.log(`${this.name}的价格:${this.price}...`);
},
};
}
let banana = new Fruits("香蕉", 10);
banana.sayName();
banana.sayPrice();
console.log(banana);
function myNew(Fn, ...args) {
let obj = Object.create(null);
obj.__proto__ = Fn.prototype;
let ret = Fn.call(obj, ...args);
return ret instanceof Object ? ret : obj;
}
let banana2 = myNew(Fruits, "香蕉2号", 20);
banana2.sayName();
banana2.sayPrice();
console.log(banana2);
未完待续…