关于JS构造函数的一个问题:
var hm = {};
new function(name){
hm[name] = this;
}("hello")
有人能给我一些关于这个构造函数如何运行的解释(例如哪个部分首先运行)
答案 0 :(得分:2)
首先var hm
成为对象,然后调用new
匿名function
并将("hello")
传递到name
参数。这里要理解的重要一点是,当您在函数名或匿名函数之后看到()
有或没有任何参数时,它会调用该函数。在这种情况下,new
关键字以及函数内部存在this
属性的事实使其成为构造函数。构造函数中的hm
根据name
参数创建一个属性,并将new
实例本身分配给hm[name]
,因为this
指的是new
hm.hello
实例。最终结果是hm['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
请记住,关键字Bob
是指实例本身。在上面的示例中,我通过调用Sally
new
个实例创建了Person
和this
个对象。通过在Constructor方法中返回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()
因为,就Bob
而言,this
和console.log(Bob.said);
console.log(Bob.lastName);
Bob.said = "Now you're getting it.";
console.log(Bob.didWhat());
是同义词。
如果您只想访问某个属性,请执行以下操作:
PIDFile