[英]How shadowing properties works in Object orientated programming with same name property
const myDate = new Date(1995, 11, 17);
console.log(myDate.getYear()); // 95
myDate.getYear = function() {
console.log('something else!')
};
myDate.getYear(); // 'something else!'
In this uploaded code the expected output is "something else" but I cannot understand how it will create shadowing when we define a object with the same name in Object prototype and how constructor function work on it In this uploaded code the expected output is "something else" but I cannot understand how it will create shadowing when we define a object with the same name in Object prototype and how constructor function work on it
Javascript inheritance works by defineing new methods on an object instance of a prototype class. Javascript inheritance 通过在原型 ZA2F2ED4F8EBC2CBB16C21A29DC40 的 object 实例上定义新方法来工作。 Eg.
例如。 if you are extending a class Base you make a new function and set its protype to an instance of Base and then add whatever method you would want extra on that instance.
如果您要扩展 class Base ,则创建一个新的 function 并将其原型设置为 Base 的实例,然后在该实例上添加您想要额外的任何方法。
An instance is a empty object with a pointer to the prototype.一个实例是一个空的 object,带有一个指向原型的指针。 The logic in accessing a property is to check its own object first, then fllow the prototype chain and eventually return
undefined
when a property isn't in any.访问属性的逻辑是首先检查它自己的 object,然后遍历原型链并最终在属性不存在时返回
undefined
。 Eg.例如。 if you write this.getYear before and after setting it you will get two different results because the accessor will start finding the property on the instance and then end its search.
如果您在设置它之前和之后编写 this.getYear,您将得到两个不同的结果,因为访问器将开始在实例上查找属性,然后结束其搜索。
V8 and modern JS engines has oprtimizations to not have to go down this rabbit hole, but it should still work the same as if it still was a linked list of objects. V8 和现代 JS 引擎进行了优化,不必将 go 放到这个兔子洞里,但它仍然应该像对象的链接列表一样工作。
And of course.而且当然。 Any property can be a method and you cannot have a method and a property have the same name since they share namespace.
任何属性都可以是方法,并且您不能让方法和属性具有相同的名称,因为它们共享命名空间。 Eg.
例如。 you could do this
myDate.getYear = 2022;
你可以这样做
myDate.getYear = 2022;
such that myDate.getYear
would return 2022
, but myDate.getYear()
would end with a application error since the property does not hold a function object that can be applied.这样
myDate.getYear
将返回2022
,但myDate.getYear()
将以应用程序错误结束,因为该属性不包含可以应用的 function object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.