1.constructor方法的特点?
constructor方法通过new命令生成实例对象时,会自动调用该方法,如果没有显示定义constructor方法,会默认添加。
constructor方法可以返回一个全新的对象,可能导致本来的构造函数里面别的方法没作用。
类的构造函数不使用new没办法调用,会报错。
2.this代表什么意思?
this在类的方法内部默认指向类的实例,但如果this写在自己的方法中,外部调用this会指向该方法运行时的环境
3.__proto__和 prototype分别表示什么意思?两者有什么区别?
每个对象(包括函数、函数的prototype对象)都有一个__proto__属性,她指向创建该对象的函数的prototype属性。
prototype 是原型,是Function对象才有的属性;实例对象没有prototype属性,但是有私有属性__proto__属性。
4、下面程序对吗?为什么?
Student类必须在constructor方法中调用super方法,否则会报错。
这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
class Person{ /* ... */ }
class Student extends Person {
constructor() {
// super()
}
}
let cp = new Student();
5、编写程序使用ES6定义 Person类,包括类实例属性(name,age),实例方法say()该方法
返回name和age字符串
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
say = function(){
return this.name + this.age;
}
}
let person = new Person('zdx',18);
console.log(person.say());
6、下面程序执行结果为: true
var p=new Person();
console.log(p.__proto__===Person.prototype)
7、下面程序正确吗?错在哪里?如何改正?
应该先调用super方法在执行this,子类没有this对象,调用之后才能继承父类的this对象。
super(x, y)
this.color = color;
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class ColorPoint extends Point {
constructor(x, y, color) {
this.color = color; // ReferenceError
super(x, y);
}
}
var cp=new ColorPoint(10,20,'red');
8、下面程序执行结果为?
(静态方法直接通过类调用,不能通过实例对象调用)
class Parent {
static myMethod(msg) {
console.log('static', msg);
}
myMethod(msg) {
console.log('instance', msg);
}
}
class Child extends Parent {
static myMethod(msg) {
super.myMethod(msg);
}
myMethod(msg) {
super.myMethod(msg);
}
}
Child.myMethod(1); // static 1
var child = new Child();
child.myMethod(2); // instance 2
9、请利用class重新定义Cat,并让它从已有的Animal继承,然后新增一个方法say(),
返回字符串’Hello, xxx!’
class Animal {
constructor(name) {
this.name = name;
}
}
.....
class Animal {
constructor(name) {
this.name = name;
}
}
class Cat extends Animal{
constructor(name){
super(name);
}
say = function(){
return `hello,${this.name}`;
}
}
var cat1 = new Cat('kitty');
console.log(cat1.say()); //hello,kitty
10、.接上面程序分析下面代码执行结果为: 测试失败!
var kitty = new Cat('Kitty');
var doraemon = new Cat('哆啦A梦');
if ((new Cat('x') instanceof Animal) && kitty && kitty.name === 'Kitty' && kitty.say &&
typeof kitty.say === 'function' && kitty.say() === 'Hello,Kitty!' &&
kitty.say === doraemon.say) {
console.log('测试通过!');
} else {
console.log('测试失败!');
}
class Animal {
constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
super(name);
}
say = function () {
return `Hello,${this.name}!`;
}
}
var kitty = new Cat('Kitty');
var doraemon = new Cat('哆啦A梦');
if ((new Cat('x') instanceof Animal) && kitty && kitty.name === 'Kitty' && kitty.say &&
typeof kitty.say === 'function' && kitty.say() === 'Hello,Kitty!' &&
kitty.say === doraemon.say) {
console.log('测试通过!');
} else {
console.log('测试失败!');
}
console.log(kitty.say === doraemon.say) //false不同的方法
11、以下代码输出的结果是(typeof (new (class { class () {} })));
A、 “function”
B、 "object"
C、 “undefined”
D、 Error