Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

basis review #65

Open
ynchuan opened this issue Aug 11, 2019 · 12 comments
Open

basis review #65

ynchuan opened this issue Aug 11, 2019 · 12 comments

Comments

@ynchuan
Copy link
Owner

ynchuan commented Aug 11, 2019

基本数据类型

number string boolean undefined null symbol

typeof

一般只能返回如下几个结果:"number"、"string"、"boolean"、"object"、"function" 和 "undefined"

  • 运算数为数字 typeof(x) = "number"
  • 字符串 typeof(x) = "string"
  • 布尔值 typeof(x) = "boolean"
  • 对象,数组和null typeof(x) = "object"
  • 函数 typeof(x) = "function"

new

function new(func) {
    let target = {};
    target.__proto__ = func.prototype;
    let res = func.call(target);
    //排除 null 的情况
    if (res && typeof(res) == "object" || typeof(res) == "function") {
    	return res;
    }
    return target;
}

instanceof

function instance_of(L, R) {//L 表示左表达式,R 表示右表达式 

    var O = R.prototype;   // 取 R 的显示原型 

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

    while (true) {    

        if (L === null)      

             return false;   

        if (O === L)  // 当 O 显式原型 严格等于  L隐式原型 时,返回true

             return true;   

        L = L.__proto__;  

    }

}

commonjs与es6模块化区别

CommonJS是对模块的浅拷贝,ES6 Module是对模块的引用。

@ynchuan
Copy link
Owner Author

ynchuan commented Aug 11, 2019

var proto = new Object;
var oProto = Object.prototype;
var oRoot = Object.prototype.__proto__;

Object.create = Object.create || function (obj) {
    var Fn = function () {};
    Fn.prototype = obj;
    return new Fn;
};

var Ta = function () {

};
proto.add = function () {

};
proto.constructor = function () {

};
Ta.prototype = proto;

var ta = new Ta;
console.log(ta);
console.log(Ta.prototype);
console.log(ta.__proto__ === proto);
console.log(proto.__proto__ === oProto);
console.log(proto.__proto__.__proto__ === oRoot);


var T = function () {

};
T.prototype.add = function () {

};

var t = new T;

console.log(t);
console.log(T.prototype);

@ynchuan
Copy link
Owner Author

ynchuan commented Aug 12, 2019

class A {}
class B extends A {}

var b = new B;
console.log(b instanceof A);

// ---------------------------

var A = function A() {};

var B = function B() {};
var a = new A;
a.constructor = B;
B.prototype = a;

var b = new B;
console.log(b instanceof A);

// ---------------------------

function _instanceof(obj, Fn) {
    var ret = false;
    var proto;
    while ((proto = obj.__proto__) != null) {
        if (proto === Fn.prototype) {
            ret = true;
            break;
        }
        obj = proto;
    }
    return ret;
}
var is = _instanceof(b, A);
console.log(is);

@ynchuan
Copy link
Owner Author

ynchuan commented Aug 12, 2019

var A = function () {
    this.a = 1;
};
A.prototype.m1 = function () {};

var create = function (Fn) {
    var Tmp = function () {};
    Tmp.prototype = Fn.prototype;
    var tmp = new Tmp;
    tmp.constructor = Tmp;
    return tmp;
};

var extend = function (Fn, obj) {
    var Ret = function () {
        Fn.call(this);
        Object.keys(obj).forEach((o) => {
            this[o] = obj[o];
        });
    };
    Ret.prototype = create(Fn);
    return Ret;
};

var B = extend(A, {
    name: 'B',
    type: 'func'
});
var b = new B;
var a = new A;
console.log(b instanceof A);
console.log(b.__proto__);

@ynchuan
Copy link
Owner Author

ynchuan commented Aug 12, 2019

function _typeof(obj) {
    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
            return typeof obj;
        };
    }
    else {
        _typeof = function _typeof(obj) {
            return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
    }
    return _typeof(obj);
}

function _possibleConstructorReturn(self, call) {
    if (call && (_typeof(call) === "object" || typeof call === "function")) {
        return call;
    }
    return _assertThisInitialized(self);
}

function _assertThisInitialized(self) {
    if (self === void 0) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }
    return self;
}

function _getPrototypeOf(o) {
    _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
        return o.__proto__ || Object.getPrototypeOf(o);
    };
    return _getPrototypeOf(o);
}

function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function");
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            writable: true,
            configurable: true
        }
    });
    if (superClass) _setPrototypeOf(subClass, superClass);
}

function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
        o.__proto__ = p;
        return o;
    };
    return _setPrototypeOf(o, p);
}

function _instanceof(left, right) {
    if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
        return !!right[Symbol.hasInstance](left);
    }
    else {
        return left instanceof right;
    }
}

function _classCallCheck(instance, Constructor) {
    if (!_instanceof(instance, Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}

var A = function A() {
    "use strict";

    _classCallCheck(this, A);
};

var B =
    /*#__PURE__*/
    function (_A) {
        "use strict";

        _inherits(B, _A);

        function B() {
            _classCallCheck(this, B);

            return _possibleConstructorReturn(this, _getPrototypeOf(B).apply(this, arguments));
        }

        return B;
    }(A);

@ynchuan
Copy link
Owner Author

ynchuan commented Aug 16, 2019

object3 (1)

@ynchuan
Copy link
Owner Author

ynchuan commented Aug 19, 2019

var fn = function (a) {
    var t = 0;
    return function fn1(b) {
        console.log(t);
    }
};
fn('a', 'b', 'c')('d');

**函数运行栈**

// 执行一段可执行代码,创建对应的执行上下文
globalContext = {
    AO: {
        fn: undefined,
    },
    scope: [globalContext.AO, window]
};
ES = [globalContext];

// fn定义
fn.scope = [globalContext.scope];

// fn调用,创建执行上下文
fnContext = {
    AO: {
        arguments: {
            1: 'a',
            2: 'b',
            3: 'c',
            length: 3
        },
        a: undefined,
        t: undefined
    },
    scope: [fnContext.AO, ...fn.scope]
};
ES.push(fnContext);

// fn1定义
fn1.scope = [fnContext.scope];

// fn1调用执行
fn1Context = {
    AO: {
        arguments: {
            1: 'd',
            length: 1
        },
        b: undefined
    },
    scope: [fn1Context.AO, ...fn1.scope]
};
ES.push(fn1Context);

// 执行完毕
ES.pop();
ES.pop();

@ynchuan
Copy link
Owner Author

ynchuan commented Sep 10, 2019

let obj = {
  [Symbol.toPrimitive](hint) {
    switch (hint) {
      case 'number':
        return 123;
      case 'string':
        return 'str';
      case 'default':
        return 'default';
      default:
        throw new Error();
     }
   }
};

2 * obj // 246
3 + obj // '3default'
obj == 'default' // true
String(obj) // 'str'

@ynchuan
Copy link
Owner Author

ynchuan commented Jul 7, 2020

const create = function (obj) {
  function T() { }
  T.prototype = obj;
  return new T;
}
const A = function () { }
const B = function () { }
const extend = function (A, B) {
  function T() {
    B.call(this);
    this.constructor = A;
  }
  T.prototype = B.prototype;
  
  const t = new T;
  A.prototype = t;
  return A;
}
const create = function (obj) {
  function T() { }
  T.prototype = obj;
  return new T;
}
const A = function () { }
const B = function () { }
const extend = function (A, B) {
  function T() {
    B.call(this);
    this.constructor = A;
  }
  T.prototype = B.prototype;
  
  const t = new T;
  A.prototype = t;
  return A;
}

@ynchuan
Copy link
Owner Author

ynchuan commented Oct 28, 2020

function extend(Fn) {
  const Ret = function () {
    const args = Array.prototype.slice.call(arguments)
    Fn.apply(this, args)
  }
  Ret.prototype = createProtoObj(Fn)
  return Ret
}
function createProtoObj(Fn) { // 创建一个净函数
  const Tmp = function () {
    this.constructor = Fn
  }
  Tmp.prototype = Fn.prototype
  return new Tmp
}
const wrap = (cbk) => { return data => { setTimeout(() => { cbk(data) }, 1) } };

class Promise {
  constructor(cbk) {
    this.state = 'PENDING';
    this.defer = [];
    this.res = wrap((data) => {
      if (this.state !== 'PENDING') return;
      this.state = 'RES';
      this.defer.forEach((tmp) => {
        const [succ, fail, res, rej] = tmp;
        const ret = succ(data);
        if (ret instanceof Promise) {
          ret.then(res, rej);
        } else {
          res(ret);
        }
      });
    });
    this.rej = wrap((err) => {
      if (this.state !== 'PENDING') return;
      this.state = 'REJ';
      this.defer.forEach((tmp) => {
        const [succ, fail, res, rej] = tmp;
        const ret = fail(data);
        if (ret instanceof Promise) {
          ret.then(res, rej);
        } else {
          res(ret);
        }
      });
    });
    cbk(this.res, this.rej);
  }
  then(cbk, err = null) {
    const tmp = [cbk, err];
    this.defer.push(tmp);
    return new Promise((res, rej) => {
      tmp.push(res, rej);
    });
  }
  catch(cbk) {
    const tmp = [null, cbk];
    this.defer.push(tmp);
    return new Promise((res, rej) => {
      tmp.push(res, rej);
    });
  }
}

var p = new Promise((res, rej) => { res(1); });
p.then(data => console.log(data)).catch(err => console.error(err));

@ynchuan
Copy link
Owner Author

ynchuan commented Oct 28, 2020

return funcs.reduce(function (a, b) {
    return function () {
      return a(b.apply(void 0, arguments));
    };
  });

@ynchuan
Copy link
Owner Author

ynchuan commented Nov 10, 2020

class Object1 {
  constructor() {
    this.name = 'Object1'
  }
}
class Object2 extends Object1 {
  constructor() {
    super()
    this.name = 'Object2'
  }
}
class Object3 extends Object2 {
  constructor() {
    super()
  }
}

const obj3 = new Object3

const extend = function (Sup, Ctor) {
  const Tmp = function () {
    Sup.call(this)
    if (Ctor) {
      Ctor.call(this)
    }
  }
  const Fn = function () { this.constructor = Tmp }
  Fn.prototype = Sup.prototype
  Tmp.prototype = new Fn
  return Tmp
}
const Object1 = function () { this.name = "Object1" }
const Object2 = extend(Object1, function () {
  
})
const Object3 = extend(Object2)
const obj3 = new Object3
console.log(obj3.name)

@ynchuan
Copy link
Owner Author

ynchuan commented Nov 22, 2020

const isUndefined = val => val === undefined
const isObject = val => typeof val === 'object'
const isArray = val => Array.isArray(val)

const get = (obj, str) => {
  const attrs = str.split(/\.|\[|\]/)
  const _get = (obj, attr) => {
    return obj[attr]
  }
  attrs.forEach(attr => {
    if (attr) {
      if (isArray(obj)) {
        attr = parseInt(attr)
        obj = _get(obj, attr)
      } else if (isObject(obj)) {
        obj = _get(obj, attr)
      } else {
        obj = undefined
      }
    }
  })
  return obj
}

const tmp1 = { a: { b: ['c'] } }
const result = get(tmp1, 'a.b[0]')
console.log(result)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant