您的位置:首页 > Web前端 > JavaScript

js 构造函数(construction)与原型(prototype)

2014-12-24 11:21 239 查看

1.面向对象:js原型

java有class和instance,js只有构造函数(function Cat(name,age){this.name=name;this.age=age}),为了实现数据共享和抽象出通用的属性,加了一个原型prototype

eg:

function Cat(name,age){

this.name = name;//这里的this相当于java里面的instance

this.age = age;

this.work = function(){

alert("I am working");

}

}

var cat1 = new Cat("cat1",13);

var cat2 = new Cat("cat2",15);

cat1和cat2的都有work属性,但是一样的属性,明显是多余的,造成浪费,可以抽象出原型出来

function Dog(name,age){

this.name = name;

this.age = age;

}

Dog.prototype = {work:function(){alert("I am working!")}}或者

Dog.prototype.work = function(){

alert("I am working");

}

2.封装:

原始模式:var cat = {};cat.name = "cat1";cat.id = "id1";

原始模式改进:var cat = function cat(name,id){return {name:name,id:id}},相当于调用函数

构造函数模式:function(name,id){this.name = name;this.id=id}

js中构造函数在初始化的时候加new和不加new的区别

function Dog(name,age){

this.name = name;

this.age = age;

}

Dog.prototype = {work:function(){alert("I am working!")}}

var dog1 = Dog("dog1",12);//这只是相当于调用普通函数,原型work不会生成,调用work属性会报错

var dog2 = new Dog("dog2",13);//这里是调用构造函数,初始化原型work

var dog3 = new Dog("dog3",14);

dog2.constructor == Dog; dog3.constructor == Dog

为了解决从原型对象生成实例的问题,Javascript提供了一个构造函数(Constructor)模式。

所谓"构造函数",其实就是一个普通函数,但是内部使用了this变量。对构造函数使用new运算符,就能生成实例,并且this变量会绑定在实例对象上。

3.继承

(1)对象冒充

function ClassA(sColor) {
this.color = sColor;
this.sayColor = function () {
alert(this.color);
};
}

function ClassB(sColor) {
}

function ClassB(sColor) {
this.newMethod = ClassA;
this.newMethod(sColor);
delete this.newMethod;
}


在这段代码中,为 ClassA 赋予了方法 newMethod(请记住,函数名只是指向它的指针)。然后调用该方法,传递给它的是 ClassB 构造函数的参数 sColor。最后一行代码删除了对 ClassA 的引用,这样以后就不能再调用它。

所有新属性和新方法都必须在删除了新方法的代码行后定义。否则,可能会覆盖超类的相关属性和方法:

function ClassB(sColor, sName) {
this.newMethod = ClassA;
this.newMethod(sColor);
delete this.newMethod;

this.name = sName;
this.sayName = function () {
alert(this.name);
};
}

var objA = new ClassA("blue");
var objB = new ClassB("red", "John");
objA.sayColor();	//输出 "blue"
objB.sayColor();	//输出 "red"
objB.sayName();		//输出 "John"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: