1.作用:
改变this指向
2.使用
A.父子类的继承
<html>
<head>
</head>
<body>
<script type="text/javascript">
// 定义父类
function Parent(name) {
this.name = name;
this.sayName = function () {
// alert(this.name);
console.log(this.name);
}
}
// 定义子类
function Child(name, password) {
this.passsword = password;
this.info = function () {
// alert(this.password);
console.log(this.passsword);
}
// 此句代码就实现了继承
Parent.call(this, name);
}
// 创建对象
var parent = new Parent("zhangsan");
var child = new Child("lisi", "123");
parent.sayName(); // zhangsan
child.info(); // 123
child.sayName(); // lisi
</script>
</body>
</html>
B.方式一 Object.create()
原生方式继承
<script type="text/javascript">
// 方式1继承
// function Person(name, age) {
// this.name = name;
// this.age = age;
// }
// function Animal() {
// }
// Animal.prototype.info = info;
// function info() {
// alert(this.name + " , " + this.age);
// }
// Person.prototype = Object.create(Animal.prototype);
// Person.prototype.constructor = Person;
// var p1 = new Person('lisi', 60);
// p1.info();
</script>
C.方式二
<script type="text/javascript">
// function Person(name, age) {
// this.name = name;
// this.age = age;
// }
// function info() {
// alert(this.name + " , " + this.age);
// }
// var p1 = new Person('lisi', 60);
// p1.show=info; //对对象添加属性,不优雅
// p1.show();
</script>
D.方式三 call()
<script type="text/javascript">
function Person(name, age) {
this.name = name;
this.age = age;
}
function info() {
console.log(this.name + " , " + this.age);
}
var p1 = new Person('lisi', 60);
info.call(p1);
p1.info();
</script>