在构造函数内部具有不同值的此属性

时间:2019-06-30 17:36:11

标签: javascript oop constructor this

我知道在构造函数的开头这是空的,并且一直填充到它自动返回为止。

function Elf(_name, _weapon) {
	
  //empty this
	console.log('this a', this); // {}

	this.name = _name;
	this.weapon = _weapon;
	
	// this with props
	console.log('this b', this); // {name: "Sam", weapon: "bow"}
}

let sam = new Elf("Sam", "bow"); 

在节点控制台和此代码段中,结果是我期望的:

this a {}
this b { "name": "Sam", "weapon": "bow" }

但是在Chrome的控制台中,我得到了:

   this a Elf {}
name: "Sam"
weapon: "bow"
__proto__: Object

this b Elf {name: "Sam", weapon: "bow"}
name: "Sam"
weapon: "bow"
__proto__: Object

为什么这些名称和武器属性已经填写?如果您要提到起重,并且对此的引用已成为全球性的,那么为什么这两本原木之间的区别呢?

1 个答案:

答案 0 :(得分:-2)

在chrome控制台中尝试以下代码

function Elf(_name, _weapon) {
    console.log('before', this.name);

    this.name = _name;
    this.weapon = _weapon;

    console.log('after', this.name);
}

let sam = new Elf("Sam", "bow"); 

您将获得预期的结果。也许在chrone控制台中登录不是“立即”,因此this在显示之前已填充值。