JS构造函数的运行顺序

Running order of JS constructor

本文关键字:顺序 运行 构造函数 JS      更新时间:2023-09-26

关于JS构造函数的一个问题:

var hm = {};
new function(name){
    hm[name] = this;
}("hello")

谁能给我一些关于这个构造函数如何运行的解释(比如哪个部分先运行)

首先var hm成为一个对象,然后调用一个new匿名function("hello")传递到name参数中。这里要了解的重要一点是,当您看到函数名称或匿名函数后带有或不带有任何参数的()时,它会调用该函数。在这种情况下,new 关键字和函数内部存在 this 属性的事实使其成为构造函数。 构造函数内部的hm基于 name 参数创建一个属性,并将new实例本身分配给 hm[name] ,因为this引用每个new实例。最终结果是hm.hellohm['hello']现在引用new实例。当然,所有代码都按照标准的操作顺序从上到下运行,例如分配前的字符串解析。另外,请注意,这不起作用:

func('wow');
var func = function(x){
  console.log(x);
}

这将起作用:

func('wow');
function func(x){
  console.log(x);
}

如果你完全不了解构造函数,你应该知道使用了构造函数,所以你可以拥有类似对象的多个实例。例如:

function Person(last, first, middle){
  this.lastName = last; this.firstName = first; this.middleName = middle;
  this.said = this.ate = '';
  this.saySomething = function(anything){
    this.said = anything;
    return this;
  }
  this.eatSomething = function(food){
    this.ate = food;
    return this;
  }
  this.didWhat = function(){
    var m = this.middleName ? ' '+this.middleName  : '';
    var n = this.firstName+m+' '+this.lastName;
    if(this.said){
      n += ' said, "'+this.said+'"';
      n += this.ate ? ', and' : '.';
    }
    if(this.ate){
      n += ' ate '+this.ate+'.';
    }
    return n;
  }
}
var Bob = new Person('Small', 'Bob', 'Richard');
Bob.saySomething('This programming stuff is pretty cool.').eatSomething('Some Vegan Food');
console.log(Bob.didWhat());
var Sally = new Person('Jones', 'Sally');
Sally.saySomething("It just takes time, but you'll get it.");
console.log(Sally.didWhat());

请记住,关键字 this 是指实例本身。在上面的示例中,我通过调用Personnew实例创建了BobSally对象。通过在构造函数方法中返回this,您可以链接方法,因为执行方法的结果是实例本身。

请注意,

Bob.saySomething('This programming stuff is pretty cool.').eatSomething('Some Vegan Food');

Bob.saySomething('This programming stuff is pretty cool.');
Bob.eatSomething('Some Vegan Food');

因为,就.eatSomething()而言,Bobthis是同义词。

如果您只想访问某个属性,则如下所示:

console.log(Bob.said);
console.log(Bob.lastName);
Bob.said = "Now you're getting it.";
console.log(Bob.didWhat());