发布于 2016-10-07 21:26:11 | 204 次阅读 | 评论: 0 | 来源: 网友投递
这里有新鲜出炉的Javascript教程,程序狗速度看过来!
JavaScript客户端脚本语言
Javascript 是一种由Netscape的LiveScript发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
call() 方法
call() 方法是与经典的对象冒充方法最相似的方法。它的第一个参数用作 this 的对象。其他参数都直接传递给函数自身。例如:
function sayHello(sPrefix,sSuffix) {
alert(this.name + ”says“ + sPrefix + sSuffix);
};
var obj = new Object();
obj.name = "Tom";
sayHello.call(obj, "Hello ", "World.");
要与继承机制的对象冒充方法一起使用该方法,只需将前三行的赋值、调用和删除代码替换即可:
function ClassA(sColor) {
this.color = sColor;
this.sayColor = function () {
alert(this.color);
};
}
function ClassB(sColor, sName) {
//this.newMethod = ClassA;
//this.newMethod(color);
//delete this.newMethod;
ClassA.call(this, sColor);
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
apply() 方法
apply() 方法有两个参数,用作 this 的对象和要传递给函数的参数的数组。例如:
function sayColor(sPrefix,sSuffix) {
alert(sPrefix + this.color + sSuffix);
};
var obj = new Object();
obj.color = "blue";
sayColor.apply(obj, new Array("The color is ", "a very nice color indeed."));
该方法也用于替换前三行的赋值、调用和删除新方法的代码:
function ClassB(sColor, sName) {
//this.newMethod = ClassA;
//this.newMethod(color);
//delete this.newMethod;
ClassA.apply(this, new Array(sColor));
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
function ClassB(sColor, sName) {
//this.newMethod = ClassA;
//this.newMethod(color);
//delete this.newMethod;
ClassA.apply(this, arguments);
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
我们可以看到这两个方法能够很好的代替原始的对象冒充,使写法上变得稍微简单。但是这些方法的弊端是子类不能继承父类在原型链上声明的方法或属性,针对这个问题下一篇文章将会介绍JavaScript中另一种实现继承的方式—原型链继承。