批改状态:合格
老师批语:以后不要这样提交作业了, 多天作业一天提交, 效果并不好
写一个构造函数来创建对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>构造函数创建对象</title>
</head>
<body>
<script>
//创建构造函数
var CreateObj=function () {
this.myname='php';
this.age=20;
this.get=function (a,b) {
var area='中国';
return '我的名字是:'+ a +',年龄是:'+ b +',国籍是:'+area;
}
};
// 创建构造函数的实例 obj1
var obj1=new CreateObj();
//用实例访问
console.log(obj1.myname);
console.log(obj1.age);
console.log(obj1.get(obj1.myname,obj1.age));
console.log(obj1.get('JavaScript',22));
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
运行结果:

2. 向构造函数的prototype中添加成员,实现数据在实例间共享
静态成员和原型成员
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>静态成员与原型成员</title>
</head>
<body>
<script>
//创建构造函数
var CreateObj=function () {
this.myname='php';
this.age=20;
this.get=function (a,b) {
var area='中国';
return '我的名字是:'+ a +',年龄是:'+ b +',国籍是:'+area;
}
};
//创建静态成员
CreateObj.tel='15200001234';
CreateObj.hello=function () {
return '欢迎来到我的国家';
}
//访问静态成员
console.log('访问静态属性:'+CreateObj.tel);
console.log('访问静态方法:'+CreateObj.hello());
// 创建构造函数的实例 obj1
var obj1=new CreateObj();
//构造函数实例不能访问静态成员
// console.log(obj1.tel);
// console.log(obj1.hello());
//创建原型成员 prototype`, 原型属性
CreateObj.prototype.tel1='15200001234';
CreateObj.prototype.hello1=function () {
return '欢迎来到我的国家';
}
//用构造函数的实例 obj1 访问原型成员
console.log('用构造函数的实例 obj1 访问原型属性:'+obj1.tel1);
console.log('用构造函数的实例 obj1 访问原型方法:'+obj1.hello1());
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
运行结果

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号