首先明确this在javascript当中的指的是调用者,在java中指的是当前对象,这两者有本质区别 JavaScript中没有类的概念,继承描述对象之间的关系,继承关键在于子类获取父类的成员及方法的方式
1. 对象冒充
function Parent(name)
{
this.name = name;
this.sayHello =
function()
{
alert(
this.name)
}
}
function Child(name, age)
{
this.method = Parent;
this.method(name);
delete this.method;
this.age = age;
this.sayWorld =
function()
{
alert(age);
}
}
var parent =
new Parent(
"张三");
var child =
new Child(
"李四",
20);
parent.sayHello();
child.sayHello();
child.sayWorld();
2. call 方法方式
function test(str, str2)
{
alert(
this.name +
", " + str +
", " + str2);
}
var object =
new Object();
object.name =
"zhangsan";
test.call(object,
"JavaScript",
"hello");
function Parent(name)
{
this.name = name;
this.sayHello =
function()
{
alert(name);
}
}
function Child(name, age)
{
Parent.call(
this, name);
this.age = age;
this.sayWorld =
function()
{
alert(age);
}
}
var parent =
new Parent(
"张三");
var child =
new Child(
"李四",
20);
parent.sayHello();
child.sayHello();
child.sayWorld();
3. apply方法方式
function Parent(name)
{
this.name = name;
this.sayHello =
function()
{
alert(name);
}
}
function Child(name, age)
{
Parent.apply(
this,
new Array(name));
this.age = age;
this.sayWorld =
function()
{
alert(age);
}
}
var parent =
new Parent(
"张三");
var child =
new Child(
"李四",
30);
parent.sayHello();
child.sayHello();
child.sayWorld();
4. 原型链方式(prototype chain )
function Parent()
{
}
Parent.prototype.name =
"张三";
Parent.prototype.sayHello =
function()
{
alert(this.name);
}
function Child()
{
}
Child.prototype =
new Parent();
Child.prototype.age =
20;
Child.prototype.sayWorld =
function()
{
alert(this.age);
}
var child =
new Child();
child.sayHello();
child.sayWorld();
5. 混合方式(克服了原型琏的弊端)
function Parent(name)
{
this.name = name;
}
Parent.prototype.sayHello =
function()
{
alert(
this.name);
}
function Child(name, age)
{
Parent.call(
this, name);
this.age = age;
}
Child.prototype =
new Parent();
Child.prototype.sayWorld =
function()
{
alert(
this.age);
}
var child =
new Child(
"李四",
30);
child.sayHello();
child.sayWorld();
转载请注明原文地址: https://ju.6miu.com/read-5706.html