我正在阅读有关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
答案 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'