在javascript中无法理解类到函数的映射

时间:2017-02-03 06:35:38

标签: javascript ecmascript-6

class Parent {
    print() {
        console.log('hey i am parent');
    }
}

class Child extends Parent {
    constructor() {
        super();
    }
    print() {
        console.log('hey i am child');
    }
}

x = new Parent();
console.log(Object.getPrototypeOf(x))
x.print();

虽然x的[[prototype]]是一个空对象,但它仍然可以访问在Parent类中定义的print()函数。

我无法理解为什么Object.getPrototypeOf(x)是一个空对象。

2 个答案:

答案 0 :(得分:3)

它在那里,只是不可枚举的。试试这个:

Object.getOwnPropertyNames(Object.getPrototypeOf(x));

// ["constructor", "print"]



class Parent {
  print() {
    console.log('hey i am parent');
  }
}

class Child extends Parent {
  constructor() {
    super();
  }
  print() {
    console.log('hey i am child');
  }
}

x = new Parent();
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(x)));
x.print();




答案 1 :(得分:1)

是什么让你认为它是空的?它具有printObject.prototype属性,但它们不可枚举,默认情况下不会在控制台上显示。 (当然它确实有[{prototype]]链接到li a.accordion-trigger(href='#accordion4', data-accord-group='group1') p(style='color:white;') 2. Subjects Average Pass Percentage : #accordion4.accordion-content.collapsed(ng-controller='ListController2', scroll='') form(ng-submit='addNew()') table.table.data.table-bordered thead tr th Subject Name th Year-Sem-Branch-Sec th No.of.Students Appeared (A) th Passed (B) th Pass Percentage (B/A*100) th input.btn.btn-primary.add.pull-right(type='submit', value='Add New') tbody tr(ng-repeat='subjectAverage in subjectAverages') td.data input(type='text', ng-model='subjectAverage.subjectName', required='') td.data input(type='text', ng-model='subjectAverage.yearSem', required='') td.data input(type='text', ng-keyup='calculatePercentage(subjectAverage)', ng-model='subjectAverage.studentsAppeared', required='') td.data input(type='text', ng-keyup='calculatePercentage(subjectAverage)', ng-model='subjectAverage.studentsPassed', required='') td.data input(type='text', ng-model='subjectAverage.percentage', disabled='disabled') td input.btn.btn-danger.pull-right.delete(type='button', ng-click='removeRow($index)', value='Remove') table tr td Average : td input(type='text', ng-model='subjectAverages[0].average') h3 Faculty text box (optional): .form-group textarea#comment.form-control(rows='3', ng-model='subjectAverages[0].facultyComment') button.btn.btn-default(type='submit', ng-click='saveavg()') Save ,但是如何/是否显示取决于你的控制台。

要检查它们,请查看str.split