首页 > Web开发 > 详细

js new关键字

时间:2018-11-23 00:54:43      阅读:200      评论:0      收藏:0      [点我收藏+]

实现new 关键字只需4步

1. 声明一个对象;

2. 把这个对象的__proto__ 指向构造函数的 prototype;

3. 以构造函数为上下文执行这个对象;

4. 返回这个对象。

简洁的代码示例如下:

function _new () {
	var f = Array.prototype.shift.call(arguments);
	var o = Object.create(f.prototype);
	f.apply(o, arguments);
	return o;
}

使用如下:

function Pers (name, age) {
	this.name = name;
	this.age = age;
	this.speak = function () {
		console.log(this.name);
	}
}

var p2 = _new(Pers, ‘xiaohua‘, 100);

console.log(p2);

p2.speak();

 

js new关键字

原文:https://www.cnblogs.com/hanguozhi/p/10005197.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!