我在函数内部创建了一个对象。我想在一个中调用对象方法 言。
(function(){
s4 = function(getSection){
var self = {
name: function(getname){
console.log("Name of the Student " +getname);
},
subject: function(getsub){
console.log(" & Studying " +getsub);
}
}
return self;
}
})();

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Details</title>
</head>
<body>
<div class="hello">
<h1>Student Details</h1>
</div>
<script src="script.js"></script>
<script>
s4("5th").name("John"); //This works fine
s4("5th").subject("Python"); //This works fine
s4("5th").name("John").subject("Python"); //Shows error: SCRIPT5007: Unable to get property 'subject' of undefined or null reference
</script>
</body>
</html>
&#13;
当我致电s4("5th").name("John").subject("Python");
时
显示错误:
SCRIPT5007:无法获得财产&#39; subject&#39;未定义或空引用
请帮我解决这个问题。 提前谢谢。
答案 0 :(得分:2)
在您的方法中,返回对象。 return this
和name
中的subject.
这称为方法链接,它通过返回对象来工作。
(function() {
s4 = function(getSection) {
var self = {
name: function(getname) {
console.log("Name of the Student " + getname);
return this;
},
subject: function(getsub) {
console.log(" & Studying " + getsub);
return this;
}
}
return self;
}
})();
s4("5th").name("John");
s4("5th").subject("Python");
s4("5th").name("John").subject("Python");
&#13;
答案 1 :(得分:2)
这称为method chaining,通常通过使每个函数不返回其他值return this;
来实现:
name: function(getname){
console.log("Name of the Student " +getname);
return this;
},
subject: function(getsub){
console.log(" & Studying " +getsub);
return this;
}
然后s4("5th").name("John").subject("Python");
将有效,因为name("John")
会返回s4("5th")
的结果。
答案 2 :(得分:0)
您的代码应为
(function() {
s4 = function(getSection) {
var self = {
name: function(getname) {
console.log("Name of the Student " + getname);
return this;
},
subject: function(getsub) {
console.log(" & Studying " + getsub);
return this;
}
}
return self;
}
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Details</title>
</head>
<body>
<div class="hello">
<h1>Student Details</h1>
</div>
<script src="script.js"></script>
<script>
s4("5th").name("John"); //This works fine
s4("5th").subject("Python"); //This works fine
s4("5th").name("John").subject("Python"); //Shows error: SCRIPT5007: Unable to get property 'subject' of undefined or null reference
</script>
</body>
</html>
现在你不会因调用函数subject()
答案 3 :(得分:-1)
你的功能
name: function(getname){
console.log("Name of the Student " +getname);
}
不会返回this
。
将其更改为:
name: function(getname){
console.log("Name of the Student " +getname);
return this;
}