JavaScript面向对象之类的创建

JavaScript对象的定义:

在js中函数极为对象,对象分为二种:对象字变量产生的对象连接到Object.prototype;函数对象连接到Function.prototype

方法:当一个函数被保存为对象的一个属性时,我们称它为一个方法。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>JavaScript中的类</title>
<script type="text/javascript">
//-------第一种:函数自变量
// 创建Object类的实例,所有直接用花括号括起来的都属于Object类,这种创建的类不用实例化
//!!!不推荐使用
var obj = {
    property:'this is a property.',
    method:function(){
        return 'I am a method.'
    }
};
// 调用方法:
console.info('property:'+obj.property+'
method:'+obj.method());

//---------------第二种:函数对象
// 自定义类:其实在JavaScript中一个函数就是一个类,调用的时候必须进行实例化  -->可以使用
// !每个实例化的类都会有三个属性,只是其中一个属性是方法而已
function User(name,age){    // 虽然对类名没有强制要求,但建议类名进行大写
    // 创建属性
    this.name = name ;
    this.age = age ;
    //创建方法
    this.getInfo = function(){
        // 获得实例的变量必须加上this
        return 'name-->'+this.name+'
age-->'+this.age ;
    }
}
// 调用方法
// 实例化
var user  = new User() ;
console.info(user.getInfo());

//基于prototype进行创建    每个实例化的对象都公用统一的方法 -->强烈推荐使用
// 性能上和维护方面都是最好的
function Person(name,age){
    this.age = age ;
    this.name = name ;
}
Person.prototype.getInfo = function(){
     return 'name-->'+this.name+'
age-->'+this.age ;
};
// 调用方法
// 实例化
var person = new Person();
console.info(person.getInfo());

</script>
</head>

<body>
<button onclick="javascript:alert('属性:'+obj.property+'
方法:'+obj.method())" >第一:创建Object类的实例(不推荐)</button>
<button onclick="javascript:alert(new User('tom',12).getInfo())" >第二:自定义类(可以使用)</button>
<button onclick="javascript:alert(new Person('tom',12).getInfo())" >第三:基于原型prototype(推荐使用)</button>

</body>
</html>
原文地址:https://www.cnblogs.com/xiaotao726/p/4713117.html