手写new,instanceof

手写new

function Person(name, age, sex) {

this.name = name

this.age = age;

this.sex = sex;

}

let p1 = new Person("小康", 12, 1)

let p2 = myNew(Person, "小康", 12, 1)

function myNew(C, ...args) {

let obj = {};

obj.__proto__ = C.prototype;

let res = C.call(obj, ...args)

return typeofres == 'object' ? res : obj

}

// objectFactory(name, 'cxk', '18')

function objectFactory() {

const obj = new Object(); // const obj = {}

const Constructor = [].shift.call(arguments);

obj.__proto__ = Constructor.prototype;

const ret = Constructor.apply(obj, arguments);

return typeofret === "object" ? ret : obj;

}

/*

typeof

constructor

A instanceof B;

Object.prototype.toString.call

({}).toString.call

*/

</script>

<script src=''>

/* [].pop

function f(){}

let res = f.call(ppp,q,w,e,r);

让f执行了,里边的this变成了 ppp,

q,w,e,r 是传给f的实参;

res 是call 的执行结果;call的执行结果是谁?是f的执行结果

res 是 f的执行结果

*/

/*

开作用域

开堆内存,本次执行 this指向 堆内存

return 不引用就是this

*/

function myNew(C, name) {

let obj = {};

obj.__proto__ = C.prototype

// Person中的this指向这个堆

let res = C.call(obj, name) // 需要判断C->Person返回的是是类型

// res是call执行的返回结果;call的返回结果就是C的返回结果

// res 就是 C的执行结果

if (typeo fres == 'object') {

return res

} else {

return obj

}

}

function Person(name) {

this.name = name

}

let p1 = new Person("小明")

let p2 = myNew(Person, '小明')

let p3 = myNew(Person, '小明')

p1.__proto__ === Person.prototype

p2.__proto__ === Person.prototype

</script>

<script src=''>

/*

new的执行过程:

先开一个作用域,然后开辟一个堆内存,this指向这个堆,

形参赋值变量提升 代码执行

返回值:不是引用的话 就默认返回this

*/

// Object.prototype.toString.call()

var obj = {

name:"珠峰"

};

function fn() {

console.log(arguments)

return 666

}

let q = fn(1, 2)

let w = fn.call(obj, 55, 66)

fn.call([])

fn.call('')

// f.call(xxx,a,b,c) : 让f执行并且把f中的this换成xxx;a,b,c是传给f的实参

// call的第一个参数是用来修改函数中的this指向的,call第二个参数及以后都是

// 传给函数的实参

// call的返回结果就是f执行返的结果

function myNew(Q, name) {

let obj = {}; // 代替实现堆

// Q作用域中的this是指向这个堆的

let res = Q.call(obj, name) // res是Q的返回结果

// new的返回结果是根据函数的return是不是引用来决定的

return typeofres == 'object' ? res : obj

}

function Person(name) {

this.name = name

}

let p1 = newPerson('小红')

let p2 = myNew(Person, '小明')


instanceof

function instance_of(L, R) {

//L 表示左表达式,R 表示右表达式

L = L.__proto__; // 取 L 的隐式原型

while (true) {

if (L === null) return false;

if (R.prototype === L)

// 这里重点:当 O 严格等于 L 时,返回 true

return true;

L = L.__proto__;

}

}

若有收获,就点个赞吧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值