“混合的构造函数/原型方式”
用构造函数来定义非函数属性,用原型方式定义对象的函数属性,结果全部函数都只建立一次,而每一个对象都具备自由的对象属性实例。
function ocar(color){
this.color = color;
this.arr = new Array("s");
}
ocar.prototype.showColor = function(){
alert(this.color);
}
var car = new ocar("resd");
car.showColor();
2、为类添加新方法:
能够用prototype属性为以有的类定义新的方法:
好比为Array定义一个dequeue()方法
//建立新的方法
Array.prototype.dequeue = function(str){
this.push(str);
}
var arr = new Array("s");
arr.dequeue("a");
alert(arr.toString());
3、重定义已有的方法:
就像给已有类定义新方法同样,也能够重写类的方法。函数名只是指向函数的指针,所以能够轻易的使用它指向别的函数。从写已有方法的时候Function的第一个F要大写
修改本地类toString()方法。
Function.prototype.toString = function(){
return "重写toString";
}
function sayHi(){
alert("Hi");
}
alert(sayHi.toString);
4、类的继承:
JS类的继承有不少种,这由于JS种的继承机制并非明确规定的,而是经过模仿实现的,这意味着全部的继承细节并非彻底解释程序处理。因此咱们选择一种适合本身的方法就能够了。
1、对象冒充:
构造函数使用this关键字给全部属性和方法赋值,由于构造类只是一种函数,因此可使ClassA的构造函数成为ClassB的方法,而后调用它,ClassB就会收到ClassA的构造函数中定义的属性和方法。例如
function oren(name){
this.name = name;
this.sayName = function(){
alert(this.name);
}
}
function orenB(name,sex){
this.newfun = oren;
this.newfun(name);
delete this.newfun;
this.sex = sex;
this.showSex = function(){
alert(this.sex);
}
}
var testA = new oren("linan");
testA.sayName();
var testB = new orenB("ln","男");
testB.sayName();
testB.showSex();
全部的新属性和新方法都必须在删除了新方法的代码后定义。不然会覆盖超类的相关属性和方法。
2、call()方法:
call()方法是与经典的对象冒充方法最类似的方法。它的第一个参数用做this的对象,其余参都直接传递给函数自己。
function oren(name){
this.name = name;
this.sayName = function(){
alert(this.name);
}
}
function orenB(name,sex){
oren.call(this,name);
this.sex = sex;
this.getSex = function(){
alert(this.sex);
}
}
var test = new oren("ln");
test.sayName();
var testB = new orenB("linan","man");
testB.sayName();
testB.getSex();
这是call()方法继承的例子,这里想让oren中的关键字this等于新建立的orenB对象,所以this是第一个参数函数