![](/img/trans.png)
[英]What is the proper way to call another function from a function within the same object that will pass jslint?
[英]What is the proper way to read a value from another function?
说我有这个功能
function name(){
var first_name = "mike";
}
我想将值 first_name 传递给另一个函数——我知道你可以这样做:
function name(){
var first_name = "mike";
getName(first_name);
}
但是说我想访问它而不像那样忽略它
function name(){
var first_name = "mike";
getName()
}
在 getName 中,如何从 name() 函数访问 first_name?
function getName(){
console.log(this.first_name)
}
在 PHP 中,我知道你可以用 $this->first_name 来完成,这在 javascript 中如何完成? 另外,如果您可以在 javascript 中调用另一个函数,是否有像在 PHP $this->first_name() 中那样正确的方法
先感谢您
function name(){
var first_name = "mike";
return first_name;
}
function getName(){
var get_name=name();
alert(get_name);
}
您无法从任何其他函数访问该变量,除非您像在naga 的解决方案中一样明确传递它,因为first_name
是本地的,只有name
可以访问它。 您可能想要使用原型。
function Person(name) {
this.first_name = name || 'Mike';
}
Person.prototype = {
getName: function() {
return this.first_name;
}
};
var john = new Person('John');
console.log(john.getName()); //=> John
有点顽皮,但这是你问题的一个答案......
var first_name = "mike";
function change_name(new_name) {
first_name = new_name;
}
function get_name() {
return first_name;
}
console.log(get_name());
我个人更喜欢这样的设计模式......
var names = new function() {
// The 'this' context may change within callbacks and such,
// so this is one way to save it for later use
var self = this;
this.first_name = "mike";
this.change_name = function(new_name) {
self.first_name = new_name;
}
this.get_name = function() {
return self.first_name;
}
}
console.log(names.first_name);
console.log(names.get_name());
names.change_name("kevin");
console.log(names.first_name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.