老师 帮我看下错在哪里
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>5-4</title>
</head>
<body>
<script>
function student(){
var privateStore={};
function _set(){
this,name=name;
this.sex=sex;
this.age={};
}
this._get=function(){
return _set;
}
}
student.prototype={
_set:function(){
name="小明";
age=18;
sex="男"
}
}
var set=new student();
set._set();
var get=set._set();
//get();
</script>
</body>
</html>
问题描述:
我题目就没太理解 第一个为啥要求有个空对象 可并没有用到
正在回答 回答被采纳积分+1
同学你好,整体的思路实现有问题,导致第一个定义的对象没有被使用,且无法实现效果。这道题的重点就是将set和get方法使用this挂载到student的实例化对象上,_set和_get方法直接使用function关键字声明。
可以简单的理解为在函数中使用this定义的属性和方法, 实例化之后可以通过点(.)的当时访问到, 如果没有使用this定义的属相和方法可以理解为函数的局部属性和方法(私有的),外部不可以直接通过点的当时访问到。所以定义一个局部变量privateStore,实现数据私有化,让它们在函数外部访问不到。
具体可以结合代码中的注释理解。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
// 1、创建一个构造函数student
function student() {
// student中使用字面式定义一个空对象privateStore,用来存放私有的数据。
var privateStore = {};
// 2、 student中定义一个函数_set , 用来设置学生的信息 (姓名,性别和年龄) 。
function _set(name, sex, age) {
// 给privateStore这个对象添加学生信息
privateStore.name = name;
privateStore.sex = sex;
privateStore.age = age;
};
// 3. student中定义一个函数_get , 用来获取信息 。
function _get() {
console.log(privateStore.name + " " + privateStore.sex + " " + privateStore.age);
}
// 4、student中定义一个方法set, 调用_set方法。
this.set = function (name, sex, age) {
// function set(name, sex, age) {
// return _set;
// 这里需要给_set方法传递参数,所以需要直接调用这个方法
_set(name, sex, age)
}
// 5、 student中定义一个方法get ,方法中返回函数_get。
this.get = function () {
// function get() {
return _get;
}
}
// 6. 实例化对象student,
var stu = new student();
// 并调用set方法为student添加信息 。如 ( "小明", "男", 23 )
// stu.set()("小明", "男", 23);
stu.set("小明", "男", 23) // 直接调用set方法就可以了
// 7.调用get方法即可。
// stu.get();
stu.get()()
</script>
</body>
</html>祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星