[英]Add function to constructor prototype with method with access to this from constructor instance
[英]In OPP JS can you access a method declared inside a prototype function from the constructor?
我正在閱讀有關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
在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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.