在新对象中调用原型另一个原型
Call prototype another prototype in new object
这个 returns 后面的 thisFunction.weather.day() 是未定义的。为什么?我这样做对吗?
'use scrict';
var thisFunction = function(){this.event(); };
thisFunction.prototype.weather = function(){
this.day = "Cloudy";
};
thisFunction.prototype.event = function(){
console.log(thisFunction.weather().day);
};
var g = new thisFunction();
我正在尝试在事件中调用天气函数。正如您在底部看到的那样,有一个新的变量 g 等于新的 thisFunction()。如果我在事件 thisFunction.prototype.weather().day 中调用天气函数,那一天是未定义的。为什么?
thisFunction
是你的构造函数。
它没有 .weather()
方法。所以,thisFunction.weather
是 undefined
而 thisFunction.weather()
是一个错误。
.weather()
方法在原型上,这意味着它在 thisFunction
的实例上,而不是在构造函数本身上。所以,在你的代码中,你可以这样做:
g.weather()
或者,在 .event()
方法中,您可以这样做:
thisFunction.prototype.event = function(){
console.log(this.weather());
};
要使 this.weather().day
起作用,您必须从 .weather()
方法中 return this
。
thisFunction.prototype.weather = function(){
this.day = "Cloudy";
return this;
};
thisFunction.prototype.event = function(){
console.log(this.weather().day);
};
这个 returns 后面的 thisFunction.weather.day() 是未定义的。为什么?我这样做对吗?
'use scrict';
var thisFunction = function(){this.event(); };
thisFunction.prototype.weather = function(){
this.day = "Cloudy";
};
thisFunction.prototype.event = function(){
console.log(thisFunction.weather().day);
};
var g = new thisFunction();
我正在尝试在事件中调用天气函数。正如您在底部看到的那样,有一个新的变量 g 等于新的 thisFunction()。如果我在事件 thisFunction.prototype.weather().day 中调用天气函数,那一天是未定义的。为什么?
thisFunction
是你的构造函数。
它没有 .weather()
方法。所以,thisFunction.weather
是 undefined
而 thisFunction.weather()
是一个错误。
.weather()
方法在原型上,这意味着它在 thisFunction
的实例上,而不是在构造函数本身上。所以,在你的代码中,你可以这样做:
g.weather()
或者,在 .event()
方法中,您可以这样做:
thisFunction.prototype.event = function(){
console.log(this.weather());
};
要使 this.weather().day
起作用,您必须从 .weather()
方法中 return this
。
thisFunction.prototype.weather = function(){
this.day = "Cloudy";
return this;
};
thisFunction.prototype.event = function(){
console.log(this.weather().day);
};