在Javascript的构造函数中修改方法中对象的属性
这基本上就是我要做的,我是Javascript新手,所以请耐心听我说:在Javascript的构造函数中修改方法中对象的属性,javascript,function,constructor,Javascript,Function,Constructor,这基本上就是我要做的,我是Javascript新手,所以请耐心听我说: function Car(make) { this.make = make; var noises = ["vroom", "woosh"]; function addNoise() { noises.push("wham"); this.noises = noises; } addNoise(); } var myCar = new Car
function Car(make)
{
this.make = make;
var noises = ["vroom", "woosh"];
function addNoise()
{
noises.push("wham");
this.noises = noises;
}
addNoise();
}
var myCar = new Car("honda");
console.log(myCar.noises[2]);
现在,我想问题是当我这样做的时候。噪音=噪音;,这不是指汽车,所以当我试着做console.logmyCar.noises[2];噪音是不确定的。在我的实际代码中,addNoise的等效程序是异步运行的,因此我必须能够使noises成为该函数中的一个属性
编辑:
是的,另一个问题也涉及类似的问题。这似乎有效:
function Car(make)
{
this.make = make;
var noises = ["vroom", "woosh"];
var self = this;
function addNoise()
{
noises.push("wham");
self.noises = noises;
}
addNoise();
}
var myCar = new Car("honda");
console.log(myCar.noises[2]);
非常简单的解决方案 最好的方法是对函数进行原型化
functionon Car(make)
{
this.make = make;
this.noises = ["vroom", "woosh"];
this.addNoise();
}
Car.prototype.addNoise = function() {
this.noises.push("wham");
}
var myCar = new Car("honda");
console.log(myCar.noises[2]);
你说得对。我对你如何组织你的代码感到困惑,但是为了解决眼前的问题,你可以做addNoise.callthis;而不仅仅是增加噪音;它在addNoise中设置了您想要的值,或者干脆忽略函数定义和调用,它们只是本地的。我决定将其作为副本关闭,因为您在我的实际代码中提到,addNoise的等效程序是异步运行的