为了账号安全,请及时绑定邮箱和手机立即绑定

【九月打卡】第6天 手写 getType 和 new

标签:
JavaScript

课程名称2周刷完100道前端优质面试真题
课程章节:第8章 前端面试技能拼图6: 编写高质量代码 - 正确,完整,清晰,鲁棒
主讲老师双越
课程内容
今天学习的内容包括:
8-6 手写一个getType函数,获取详细的数据类型
8-7 new一个对象的过程是什么,手写代码表示

课程收获

获取数据类型

主要是利用 Object.prototype.toString

使用 toString() 检测对象类型

可以通过 toString() 来获取每个对象的类型。为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为 thisArg。

手写 getType

const getType = (x) => {
	let type = Object.prototype.toString.call(x);
	return type.slice(type.indexOf(' ') + 1, -1).toLowerCase();
}
console.log(getType([1, 2])) //array
console.log(getType(undefined)) // undefined
console.log(getType(new Map())) // map

new 过程

创建一个空对象,继承构造函数的原型
执行构造函数
返回之前创建的对象

复习一下 Object.create

Object.create(proto, propertiesObject)
创建一个新对象,使用proto来作为新创建对象的原型(prototype)。
以 null 为原型的对象通常用于作为 map 的替代

const alex = {
    name: "Alex",
    age: 18
}
const info = Object.create(alex, {
    city: {
        value: "Beijing"
    }
})
console.log(info) // {city: 'Beijing'}
console.log(info.__proto__) // {name: 'Alex', age: 18}

手写 new

const customNew = (constructor, ...args) => {
    // 创建对象,执行构造函数,返回
	const obj = Object.create(constructor.prototype)
	constructor.apply(obj, args);
	return obj;
}
// for test
function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype.getName = function () {
    return this.name;
}
console.log(customNew(Person, 'Alex', 18)); // Person {name: 'Alex', age: 18}

图片描述
以上,结束。

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消