ihtml5 / blog

个人博客 源码阅读*前端实践 My Blog
MIT License
6 stars 0 forks source link

javascript如何实现面向对象编程 #19

Open ihtml5 opened 7 years ago

ihtml5 commented 7 years ago

Es5

一. new命令背后发生了什么

1. 原理:

2. 相关代码

Object.create = Object.create || function(prototype) {
    var F = function () {};
    F.prototype = prototype;
    return new F();
}
function _new () {
    var args = [].slice.call(arguments);
    var constructor = args.shift();
    var context = Object.create(constructor.prototype);
    var result = constructor.apply(context,args);
    return typeof result === 'object' && result !=null ? result : context;
}

3.如何防止因没有使用new命令,而发生意外

var Tu = function(obj) {
    if ( this instanceof obj) { return obj }
   if (!(this instanceof obj) ) { return new Tu(obj);}
   // 构造函数执行一些动作
};