在OPP JS中,您可以从构造函数访问原型函数内声明的方法吗?

时间:2015-02-06 18:20:18

标签: javascript prototype

我正在阅读有关OPP js的内容,并在回顾一个例子时想知道是否在:

function Person(name){
    this.name = name;

}

Person.prototype.sayName = function(){

        var tempName = this.name;

        var saySomething = function(){

            console.log(tempName);

    }
    //return saySomething();
}

var person1 = new Person('chris');

是一种从构造函数中激活saySomething方法的方法。 例如

person1.sayName().saySomething() //which doesnt work obviously

1 个答案:

答案 0 :(得分:0)

sayName工作时返回对象:

function Person(name) {
    this.name = name;
}

Person.prototype.sayName = function() {

    var tempName = this.name;

    return {
        saySomething: function() {
            console.log(tempName);
        }
    };
};

var person1 = new Person('chris');
person1.sayName().saySomething(); // logs 'chris'