bwangel23
9/17/2016 - 11:25 PM

nodejs中new的说明

nodejs中new的说明

function pet(words) {
    this.words = words;

    console.log(this.words);
    console.log(this === global); // true
}

pet('...');

function Pet(words) {
    // this指的是函数拥有者,this只能在函数内部调用。
    this.words = words;
    this.speak = function() {
        console.log(this.words);
        console.log(this);
    }
}

// new会新创建一个对象用来替代global,让this指向这个对象
var cat = new Pet('Miao');

cat.speak();