关于JavaScript-继承属性的应用,extends call prototype
extends用法演示
<script> class Father{ constructor(x, y){ this.x = x; this.y = y; } sum(){ console.log(this.x + this.y) } } class Son extends Father{ constructor(x, y){ super(x,y); // 调用了父类中的构造函数 } } var son = new Son(1,2); var son1 = new Son(11,22); son.sum(); son1.sum(); </script>
Father构造的方法,子类使用extends能够继承父类的方法, 子类使用super即可调用.
call的使用
<script>
function fn(x, y){
console.log('我想喝手磨咖啡');
console.log(this);
console.log(x + y);
}
var o = {
name: 'andy'
};
// call第一个函数用于改变指向
fn.call(o, 1, 2);
function Star(role, age) {
this.role = role;
this.age = age;
}
var son = new Star('李白', 18)
console.log(son.role);
console.log(Star.role);
</script>
输出结果 :
我想喝手磨咖啡
Objectname: "andy"[[Prototype]]: Object
3
李白
undefined
call第一个参数能够改变this的指向
<script>
// 借用父构造函数继承属性
// 1.父构造函数
function Father(uname, age){
// this
this.uname = uname;
this.age = age;
}
Father.prototype.money = function(){
console.log(100000);
}
function Son(uname, age, score){
Father.call(this, uname, age);
this.score = score;
}
// Son利用prototype指向Father 及Son拥有了父类的所有属性
Son.prototype = new Father();
// 对象的形式修改了原型对象,别忘了利用constructor 指回原来的构造函数
Son.prototype.constructor = Son;
// 子构造函数专门的方法,由于Son在继承父类的属性后,给自己增加exam方法,所以父类是访问不到exam的
Son.prototype.exam = function() {
console.log('孩子考试');
}
var son = new Son('刘德华', 18, 100);
console.log(son);
console.log(Father.money);
console.log(Son.prototype.constructor);
console.log(son.exam());
console.log(Son.prototype.exam());
console.log(Father.prototype);
console.log(Son.prototype);
</script>

浙公网安备 33010602011771号