gpt4 book ai didi

javascript - 如何在一条语句中调用 JavaScript 对象方法(方法链)

转载 作者:行者123 更新时间:2023-11-28 18:20:11 25 4
gpt4 key购买 nike

我在函数内部创建了一个对象。我想在一个对象中调用对象方法声明。

(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>

当我调用s4("5th").name("John").subject("Python");显示错误:

SCRIPT5007: Unable to get property 'subject' of undefined or null reference

请帮我解决这个问题。提前致谢。

最佳答案

在您的方法中,返回对象。 return thisnamesubject.这称为方法链接,它通过返回一个对象来工作。

(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");

关于javascript - 如何在一条语句中调用 JavaScript 对象方法(方法链),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40012969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com