在构造函数中设置的属性将覆盖原型上的属性

Property set in constructor overrides property on prototype

本文关键字:属性 覆盖 原型 构造函数 设置      更新时间:2023-09-26

试图澄清一些原型继承基础。

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_var)返回10,因为我覆盖了原型中的值。但是,返回"原始"原型定义中设置的数字。我在想为什么。

无论原型上的first_var的值是什么,构造函数都会显式地在新创建的对象上设置该值。

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

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

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