简体   繁体   English

使用原型添加功能

[英]Using protoype to add functions

After looking through some of the other threads inheritance looks a bit complicated. 在浏览了其他一些线程之后,继承看起来有些复杂。 the why does the getAge() function not return the this._age value in Option 1? 为什么getAge()函数没有在选项1中返回this._age值? and what is best practice between Option 1 and Option 2? 方案1和方案2之间的最佳做法是什么?


Option 1 选项1

function Person(){
    this._age = 21;
}

Person.prototype.getAge(){
    return this._age;//undefined
}

var person = new Person();
person.getAge();

Option 2 选项2

function Person(){
    var _age = 21,
    getAge:function(){
        return _age;
    }
}

Finally what would be the different be between the above two and the following? 最后,以上两个与下面的有什么不同?


var person = new Person();
person.age = 21;

I just might be confusing myself. 我可能会让我感到困惑。

Try this code: 试试这个代码:

var Person = function(){
    this._age = 21;
}

Person.prototype.getAge = function(){
    return this._age;
}

var person = new Person();
alert(person.getAge());

Option 2: 选项2:

var Person = function(){
    this._age = 21;
    this.getAge=function(){
        return this._age;
    }
}
var person = new Person();
alert(person.getAge());

There's no real "best practice" to speak of. 没有真正的“最佳实践”可以说。 The issue in your first example is a simple syntax error: 第一个示例中的问题是一个简单的语法错误:

function Person(){
    this._age = 21;
}

Person.prototype.getAge = function(){
    return this._age; //21
}

var person = new Person();
person.getAge();

Option 2 also has a lot of syntax errors. 选项2也有很多语法错误。 Too many to go into detail here. 这里有太多要详细介绍的内容。 This is the best explanation of these concepts that I know of: http://javascript.crockford.com/private.html 这是我所知道的关于这些概念的最好解释: http : //javascript.crockford.com/private.html

In option 1 and your third example, external code can modify the value of _age and age respectively. 在选项1和第三个示例中,外部代码可以分别修改_ageage的值。 Which is to say that in option 1 I can come along and go: 也就是说,在选项1中,我可以走过去:

person._age = 1000;

and that will actually update the value of _age within the object. 并且实际上将更新对象中_age的值。 In the case of what you're trying to do with option 2, no functions that are declared outside the Person "class" (really an Object) can modify the value of _age , which is probably a good thing in this context. 对于尝试使用选项2的情况,在Person“类”(实际上是Object)之外声明的任何函数都不能修改_age的值,这在这种情况下可能是一件好事。

Inheritance can be easy: 继承很容易:

inheritance using underscore 使用下划线继承

or if you like ExtJS 或者如果您喜欢ExtJS

ExtJs inheritance behaviour ExtJs的继承行为

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

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