首页 > 代码库 > js 构造函数(construction)与原型(prototype)

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

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.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 dog1 = new Dog("dog2",13);//这里是调用构造函数,初始化原型work




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