了不起的NodeJS(二)

  • factory
/**
 * 无法判定对象所属类型
 */
function createPerson(name, age, job) {
    return {
        name: name,
        age: age,
        job: job,
        say: function () {
            console.log(`my name is ${this.name},age is ${this.age},job is ${this.job}`)
        }//这里不可用箭头函数,箭头函数中的this,arguments不会被绑定,会沿着父环境逐级向上寻找
    }
}
var person1 = createPerson('lyf', 22, 'node');
person1.say();
  • constructors
/**
 * 每个方法会在每个实例上创建一次,即方法不被不同实例共享
 */
function Person(name, job) {
    this.name = name;
    this.job = job;
    this.say = function () {
        console.log(`my name is ${this.name},job is ${this.job}`);
    }
}
/**
 * 1、创建一个新对象
 * 2、将构造函数作用域赋值给新对象(即this指向新对象)
 * 3、执行构造函数中代码
 * 4、返回新对象
 */
/**
 * var p1=new Person()
 * 1、var p1={}
 * 2、p1.__proto__=Person.prototype
 * 3、Person.call(p1)
 */
var person = new Person('Lyf', 'node');
person.say();
console.log(person.constructor == Person)
  • prototype
/**
 * 所有对象共同使用同一数据,当a修改后b中访问也是修改后的值
 */
function Person() {
}
Person.prototype = {
    constructor: Person,
    name: 'Lyf',
    job: 'Node',
    say: function () {
        console.log(`my name is ${this.name},job is ${this.job}`)
    }
}
var person = new Person();
person.say();
  • constructors+prototype
/**
 * 完美
 */
function Person(name, job) {
    this.name = name;
    this.job = job;
    if (typeof this.say !== 'function')//只有第一次才会创建原型方法
        Person.prototype.say = function () {
            console.log(`my name is ${this.name},job is ${this.job}`)
        }
}
var person = new Person('Lyf', 'Node');
person.say();
    原文作者:我就是L
    原文地址: https://www.jianshu.com/p/6f3a81f72fab
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞