怎样用Javascript定义一个类

JavaScript021

怎样用Javascript定义一个类,第1张

javascript是一个“基于对象”的编程语言,不是面向对象的编程语言。

你要知道javascript中的function定义的函数实际上就是Function对象实例。

例如:

function demo(x){

alert(x)

}

实际上等价于:

Function demo = new Function("x","alert(x)")

所以你如果想要用javascript来模拟面向对象编程(例如Java的类),那么就可以用function来模拟Class,用function的原型prototype或者嵌套function来模拟类的方法或者属性。下面给你一个简单的例子:

//模拟学生类,可以带参数,例如initName

function Student(initName){

var name = initName//模拟学生类的属性name

}

Student.prototype.printName = function(){ //定义Student类prototype中的printName函数

alert(this.name)

}

测试时可以这样写:

var student = new Student("张三")//创建一个“Student对象”,实际上是一个Function实例对象

student.printName() //执行student对象的printName函数

1,工厂方式:也可以带参数的!每次都要创建新函数showColor(),其实可以在工厂函数外定义该函数,每个对象共享了同一个函数,然后用o.showColor=showColor指向该方法2,构造函数方式function Car(sColor){this.color=sColorthis.showColor=function(){alert(this.color)}}var o1=new Car("red")3,原型方式4,混合的构造函数/原型方式function Car(sColor){this.color=sColorthis.drivers=new Array("mike","sue")}Car.prototype.showColor=function(){alert(this.color)}var o1=new Car("red")o1.drivers.push(“mat”)5,动态原型方法function Car(sColor){this.color=sColorthis.drivers=new Array("mike","sue")}if(typeof Car._initialized=="undefined"){Car.prototype.showColor=function(){alert(this.color)}Car._initialized=true}可以确保该方法只创建一次6,混合工厂模式建议不采用

过去一年了啊,LZ找到答案了么

我也是初学,下面我举个简单的例子吧

<html><script language="javascript">

function ClassA(){

this.color = ""

}

function ClassB(){

ClassA.call(this)//this是ClassB的对象

}

var b = new ClassB()

b.color="green"

document.write(b.color+"<br>")//green

</script></html>

定义两个类ClassA、ClassB,ClassB原本没有color这个属性,但是通过call函数将ClassA的东西都放入ClassB中,于是ClassB便继承了ClassA的属性color。