JavaScript:通过原型进行属性分配

JavaScript:通过原型进行属性分配,javascript,prototype,Javascript,Prototype,我正在努力理解以下两组代码的区别。原始代码来自,我为自己简化了一点 问题:我想我了解CodeA的工作原理Ninja.prototype.swung=false正在为函数Ninja()赋值一个新属性,因此,ninjiaA.swung的计算结果为false。然而,在CodeB中,当我们在开始时用this.swung=true声明函数Ninja()时,后面的Ninja.prototype.swung=false赋值不起作用,ninjaA.swung仍需求值为true。我不明白为什么后面的作业在Code

我正在努力理解以下两组代码的区别。原始代码来自,我为自己简化了一点

问题:我想我了解CodeA的工作原理
Ninja.prototype.swung=false
正在为函数Ninja()赋值一个新属性,因此,
ninjiaA.swung
的计算结果为false。然而,在CodeB中,当我们在开始时用
this.swung=true
声明
函数Ninja()
时,后面的
Ninja.prototype.swung=false
赋值不起作用,
ninjaA.swung
仍需求值为true。我不明白为什么后面的作业在CodeB中不起作用。有人能告诉我这件事吗

CodeA:

function Ninja(){}  
Ninja.prototype.swung = false; 
var ninjaA = new Ninja();
ninjaA.swung; //evaluates to false
CodeB:

function Ninja(){ 
  this.swung = true; 
}  
Ninja.prototype.swung = false; //I'm expecting this changes swung to false, 
                               //but it doesn't.
var ninjaA = new Ninja();      
ninjaA.swung; //evaluates to true
ninjaA.swung 1. Is swung a property of the current object - No 2. Is swung a property of the current object's prototype - Yes 2.1. Return it ninjaA.swung 1. Is swung a property of the current object? - Yes 1.1 Return it
提前非常感谢。

作为构造函数调用
Ninja
时,将值
true
分配给
swung
。在执行构造函数之前,对象将如下所示:

{
    prototype : {
        swung : false
    }
}
执行构造函数后:

{
    prototype : {
        swung : false
    },
    swung : true
}

当您请求属性
swung
时,将在每个级别检查原型链,以查看它是否存在。如果它不存在,则返回值
undefined

在JavaScript中,附加到原型的方法只有在实例上首先找不到该方法时才会被调用。

在构造函数函数中使用
this
声明属性时,它会附加到该构造函数的每个对象


当您在该构造函数的原型上声明属性时,它将保留在那里,并且该构造函数的所有对象都引用它。当对象和原型链中有同名的属性时,对象的属性将隐藏原型上的属性

思考如何在原型链中评估属性,这可能会使事情更清楚

CodeA:

function Ninja(){ 
  this.swung = true; 
}  
Ninja.prototype.swung = false; //I'm expecting this changes swung to false, 
                               //but it doesn't.
var ninjaA = new Ninja();      
ninjaA.swung; //evaluates to true
ninjaA.swung 1. Is swung a property of the current object - No 2. Is swung a property of the current object's prototype - Yes 2.1. Return it ninjaA.swung 1. Is swung a property of the current object? - Yes 1.1 Return it ninjaA.swung 1.是当前对象的属性-否 2.是当前对象原型的属性-是 2.1. 还它 CodeB:

function Ninja(){ 
  this.swung = true; 
}  
Ninja.prototype.swung = false; //I'm expecting this changes swung to false, 
                               //but it doesn't.
var ninjaA = new Ninja();      
ninjaA.swung; //evaluates to true
ninjaA.swung 1. Is swung a property of the current object - No 2. Is swung a property of the current object's prototype - Yes 2.1. Return it ninjaA.swung 1. Is swung a property of the current object? - Yes 1.1 Return it ninjaA.swung 1.摆动是当前对象的属性吗?-对 1.1退回
在代码B中,它永远不会到达原型上的属性。

我编辑了您的答案以使用
pre
标记。我发现几乎是幽默的颜色会降低答案的质量。@Dan-谢谢:)@Chaospanion-谢谢你的改变,现在看起来好多了:)+1你的新添加让事情变得非常清楚。@Anurag-谢谢,我确实认为你逐步解释的方式会帮助新手更好地理解它。