简体   繁体   English

是否可以全局访问原型变量

[英]Is it possible to access the prototype variable GLOBALLY

function Person() {}

Person.prototype.getFullName = function(){
    var name = "John Micheal";
}

var p1 = new Person();
console.log(p1.getFullName());

Here I want to access the variable "name" to my other prototypes.在这里,我想访问其他原型的变量“名称”。 Is this possible?这可能吗?

If not, Is there any other way to do ?如果没有,还有其他方法吗?

http://jsfiddle.net/KabeerRifaye/bcxqx1wj/ http://jsfiddle.net/KabeerRifaye/bcxqx1wj/

Thanks in advance.提前致谢。

You should probably go do some JavaScript tutorials.您可能应该去学习一些 JavaScript 教程。 I recommend TreeHouse or CodeSchool.我推荐 TreeHouse 或 CodeSchool。

Anyways, there are a few possible options / interpretations of your question.无论如何,您的问题有几种可能的选择/解释。

If you're just trying to get the return value you need to use the return keyword.如果您只是想获取返回值,则需要使用return关键字。 Now your console.log will output the name.现在您的console.log将输出名称。

 function Person() {} Person.prototype.getFullName = function(){ var name = "John Micheal"; return name; } var p1 = new Person(); console.log(p1.getFullName());

If you truly want to share the value between functions you need to use the this keyword.如果你真的想在函数之间共享值,你需要使用this关键字。 In this example you can set the value in setName and retrieve it with getName .在此示例中,您可以在setName设置值并使用getName检索它。

 function Person() {} Person.prototype.getName = function(){ return this.name } Person.prototype.setName = function(newName) { this.name = newName } var p1 = new Person(); p1.setName('John'); console.log(p1.getName());

These are hard concepts to learn on your own.这些都是很难自己学习的概念。 I really recommend working through some JavaScript tutorials to learn this fundamental concepts.我真的建议通过一些 JavaScript 教程来学习这个基本概念。

I updated your version => http://jsfiddle.net/bcxqx1wj/3/我更新了你的版本 => http://jsfiddle.net/bcxqx1wj/3/

I would highly recommend to use a more generic get function:我强烈建议使用更通用的 get 函数:

Person.prototype.getData = function(prop){
    if (this[prop] !== undefined) {
        return this[prop];
    } else {
        return false;
    }
}

Set function would look like this:设置函数看起来像这样:

Person.prototype.setData = function(prop, data){
    this[prop] = data;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM