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

时间:2016-09-12 13:35:43

标签: 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_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,因为我覆盖了原型中的值。但是,返回"原始"中设置的数字。原型定义。试图绕过原因。

2 个答案:

答案 0 :(得分:4)

无论原型上first_var的值如何,您的构造函数都会在新创建的对象上显式设置值。

构造函数中的代码与构造函数外部代码中的赋值完全相同,换句话说。构造函数中的代码只是代码,而构造函数this中引用的是新对象,而不是原型。

答案 1 :(得分:1)

如果对象没有属性并且该对象的原型具有该属性,则将发生原型继承。

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