将原型调用为新对象中的另一个原型

Call prototype another prototype in new object

本文关键字:原型 另一个 对象 调用 新对象      更新时间:2023-09-26

返回thisFunction.wweather.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();

我正在尝试调用事件内部的天气函数。正如你在底部看到的,有一个新的var g,它等于new thisFunction()。如果我在事件thisFunction.protype.wweather()内调用weather函数,那么day是未定义的。为什么?

thisFunction是您的构造函数。

它没有.weather()方法。因此,thisFunction.weatherundefined,而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);
};