<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>js面向对象的语法</title>
<script type="text/javascript">
//写法一
var Person=function(){
//公用方法
var pub={
initialize:true,
name:"属性",
initialize:function(){
alert("初始化");
},
getTitle:function(){
return "Person-方法";
}
};
//静态方法
Person.setName=function(value){
return value;
}
return pub;
}
//写法二
function Student(){
//创建方法
Student.prototype.sex=function(value){
return value;
}
//创建静态方法
Student.getName=function(){
return "静态方法";
}
//创建属性
Student.prototype.name="名字";
Student.prototype.getTitle=function(){
return "Student-方法";
}
}
function Student1(){
}
//写法三
var Teacher=new Object();
Teacher.setName=function(value){
return value;
}
//继承的写法
Object.extend=function(childClass,fatherClass){
for(var prototype in fatherClass){
childClass[prototype]=fatherClass[prototype];
}
return childClass;
}
// 声明一个全局对象Namespace,用来注册命名空间
Namespace = new Object();
// 全局对象仅仅存在register函数,参数为名称空间全路径,如"Grandsoft.GEA"
Namespace.register = function(fullNS)
{
// 将命名空间切成N部分, 比如Grandsoft、GEA等
var nsArray = fullNS.split('.');
var sEval = "";
var sNS = "";
for (var i = 0; i < nsArray.length; i++)
{
if (i != 0) sNS += ".";
sNS += nsArray[i];
// 依次创建构造命名空间对象(假如不存在的话)的语句
// 比如先创建Grandsoft,然后创建Grandsoft.GEA,依次下去
sEval += "if (typeof(" + sNS + ") == 'undefined') " + sNS + " = new Object();"
}
if (sEval != "") eval(sEval);
}
window.οnlοad=function(){
alert(typeof(Namespace));
var st=Object.extend(new Student(),new Person());
var stud=new Student();
//alert(stud.getTitle());
//alert(st.getTitle());
var person=new Person();
var student=new Student();
//alert(Person.setName("静态方法"));
//alert(person.name);
//alert(student.name);
//alert(Student.getName());
//alert(Teacher.setName("张家品"));
}
</script>
</head>
<body>
</body>
</html>
javascript面象对象的写法
最新推荐文章于 2023-09-08 09:33:41 发布