pas*_*rby 2 inheritance hasownproperty typescript
如果我理解正确,object.hasOwnProperty()则应在父类的继承属性上返回false。但是,以下代码在自己的属性和继承的属性上均返回true。
我的理解/代码不正确还是hasOwnPropery()不正确?如果是我,如何区分自己的属性和继承的属性?
编辑:我已经将用例添加到示例代码中。
我希望孩子的fromDb()只照顾自己的属性,相反,它将覆盖父母的设置的属性fromDb()。
class Parent {
parentProp = '';
fromDb(row: {}) {
for (const key of Object.keys(row)) {
if (this.hasOwnProperty(key)) {
if (key === 'parentProp') {
// Do some required data cleansing
this[key] = row[key].toUpperCase()
} else {
this[key] = row[key];
}
}
};
return this;
}
}
class Child extends Parent {
childProp = '';
fromDb(row: {}) {
super.fromDb(row);
for (const key of Object.keys(row)) {
if (this.hasOwnProperty(key)) {
this[key] = row[key];
}
};
return this;
}
}
let row = {
parentProp: 'parent',
childProp: 'child',
}
let childObj = new Child().fromDb(row);
console.log(childObj);
Run Code Online (Sandbox Code Playgroud)
安慰:
Child:
childProp: "child"
parentProp: "parent"
Run Code Online (Sandbox Code Playgroud)
在生成的extends代码中,将属性复制到子类中,如下所示:
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
Run Code Online (Sandbox Code Playgroud)
这意味着您的子类(d)被赋予了它自己的属性。
实际上,这与使用普通JavaScript继承没有什么不同:
function Parent() {
this.parentProp = `I'm defined by Parent`;
}
function Child() {
Parent.call(this);
this.childProp = `I'm defined by Child`;
}
let childObj = new Child();
for (const key of Object.keys(childObj)) {
console.log(key, childObj.hasOwnProperty(key));
}
Run Code Online (Sandbox Code Playgroud)
如果您给我们一些指导,说明您需要实现的目标,那么我相信我们会为您找到一种合适的机制来克服这一障碍。
对于您的特定用例,可以通过调用超类的位置来设置谁“获胜”的先例。
获得输出
childProp: "child"
parentProp: "PARENT"
Run Code Online (Sandbox Code Playgroud)
让父级运行“第二”,而不是“第一”:
class Child extends Parent {
childProp = '';
fromDb(row: {}) {
for (const key of Object.keys(row)) {
if (this.hasOwnProperty(key)) {
this[key] = row[key];
}
};
super.fromDb(row); // <-- last update wins
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
这将动态地从子项中排除父项,并从父项中排除子项...添加console.log语句以查看内部信息...
class Parent {
parentProp = '';
fromDb(row: {}) {
const ownKeys = Object.keys(new Parent());
for (const key of Object.keys(row)) {
if (ownKeys.indexOf(key) > -1) {
if (key === 'parentProp') {
// Do some required data cleansing
this[key] = row[key].toUpperCase()
} else {
this[key] = row[key];
}
}
};
return this;
}
}
class Child extends Parent {
childProp = '';
fromDb(row: {}) {
super.fromDb(row);
const ownKeys = this.getKeys();
for (const key of Object.keys(row)) {
if (ownKeys.indexOf(key) > -1) {
this[key] = row[key];
}
};
return this;
}
getKeys() {
const childKeys = Object.keys(this);
const parentKeys = Object.keys(new Parent());
return childKeys.filter( function( el ) {
return parentKeys.indexOf( el ) < 0;
});
}
}
let row = {
parentProp: 'parent',
childProp: 'child',
}
let childObj = new Child().fromDb(row);
console.log(childObj);
Run Code Online (Sandbox Code Playgroud)