Javascript 构造函数中的属性集覆盖原型上的属性

Javascript 构造函数中的属性集覆盖原型上的属性,javascript,prototype,Javascript,Prototype,试图澄清一些原型继承的基础知识 function thirdSampleObject(){ this.first_var = 3; this.update = function(){"Hi I am a function"}; } var thirdClass = new thirdSampleObject(); var fourthClass = new thirdSampleObject(); thirdClass.first_var = 5; fourthClass.first

试图澄清一些原型继承的基础知识

function thirdSampleObject(){
  this.first_var = 3;
  this.update = function(){"Hi I am a function"};
}

var thirdClass = new thirdSampleObject();
var fourthClass = new thirdSampleObject();

thirdClass.first_var = 5;
fourthClass.first_var = 7;


console.log(thirdClass.first_var);  //returns 5
console.log(fourthClass.first_var); //returns 7

thirdSampleObject.prototype.first_var = 10;

console.log(thirdClass.first_var);  //returns 5 "protectected" within it's own instance of the object
console.log(fourthClass.first_var); //returns 7 "protectected" within it's own instance of the object

var fithClass = new thirdSampleObject();
console.log(fithClass.first_var);   //returns 3 ? Wouldn't this return 10 at this point?`

我希望
console.log(fithClass.first\u var)
返回10,因为我在原型中重写了该值。但是,返回“原始”原型定义中设置的数字。我在想为什么

无论原型上的
first\u var
值是多少,构造函数都会显式地在新创建的对象上设置值


换句话说,构造函数中的代码所做的事情与构造函数之外的代码中的赋值完全相同。构造函数中的代码只是代码,在构造函数中,此指的是新对象,而不是原型。

无论原型上的first\u var值如何,构造函数都会显式设置新创建对象的值


换句话说,构造函数中的代码所做的事情与构造函数之外的代码中的赋值完全相同。构造函数中的代码只是代码,而在构造函数中,此指的是新对象,而不是原型。

如果对象不具有属性,而该对象的原型具有属性,则会发生原型继承

function thirdSampleObject(){
  this.first_var = 3;
  this.update = function(){"Hi I am a function"};
}
thirdSampleObject.prototype.first_var = 10;

var fifthClass = new thirdSampleObject();  

fifthClass.hasOwnProperty('first_var'); // returns true. i,e fifthClass object have its own property 'first_var'.

console.log(fifthClass.first_var);

delete fifthClass.first_var //here we are deleting the property from object.

fifthClass.hasOwnProperty('first_var'); // returns false

console.log(fifthClass.first_var); // returns 10

如果对象不具有该属性,而该对象的原型具有该属性,则将发生原型继承

function thirdSampleObject(){
  this.first_var = 3;
  this.update = function(){"Hi I am a function"};
}
thirdSampleObject.prototype.first_var = 10;

var fifthClass = new thirdSampleObject();  

fifthClass.hasOwnProperty('first_var'); // returns true. i,e fifthClass object have its own property 'first_var'.

console.log(fifthClass.first_var);

delete fifthClass.first_var //here we are deleting the property from object.

fifthClass.hasOwnProperty('first_var'); // returns false

console.log(fifthClass.first_var); // returns 10

在构造函数中设置实例属性。该属性将始终盖过原型中的属性集。您应该给您的问题一个有意义的标题,例如“构造函数中的属性集覆盖原型上的属性”。构造函数中的赋值与原型无关;构造函数中的
this
的值是新对象,而不是原型。@torazaburo done。在构造函数中设置实例属性。该属性将始终盖过原型中的属性集。您应该给您的问题一个有意义的标题,例如“构造函数中的属性集覆盖原型上的属性”。构造函数中的赋值与原型无关;构造函数中的
this
的值是新对象,而不是原型。@torazaburo done。明白了。拼凑了一个快速的演示,让我的头脑中的每一个动作都正常运转。非常感谢@迪玛听到这个消息很高兴!知道了。拼凑了一个快速的演示,让我的头脑中的每一个动作都正常运转。非常感谢@迪玛听到这个消息很高兴!