简体   繁体   English

在新对象中将原型称为另一个原型

[英]Call prototype another prototype in new object

This returns back thisFunction.weather.day() is undefined.. Why? 这将返回thisFunction.weather.day()未定义。为什么? Am i doing this correct? 我这样做正确吗?

 '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();

Im trying to call the weather function inside of event. 我试图在事件内部调用天气功能。 As you can see at the bottom theres a new var g that equals new thisFunction(). 如您在底部看到的,有一个新的var g等于new thisFunction()。 If I call the weather function inside event thisFunction.prototype.weather().day is undefined. 如果我在事件内部调用天气功能,则此Function.prototype.weather()。day是未定义的。 Why? 为什么?

thisFunction is your constructor function. thisFunction是您的构造函数。

It does not have a .weather() method. 它没有.weather()方法。 So, thisFunction.weather is undefined and thisFunction.weather() is an error. 因此, thisFunction.weatherundefinedthisFunction.weather()是错误。

The .weather() method is on the prototype which means its on instances of thisFunction , not on the constructor itself. .weather()方法在原型上,这意味着它在thisFunction实例上,而不在构造函数本身上。 So, in your code, you could do: 因此,在您的代码中,您可以执行以下操作:

 g.weather()

Or, inside of the .event() method, you could do this: 或者,在.event()方法内部,您可以执行以下操作:

thisFunction.prototype.event = function(){

    console.log(this.weather());
};

To make this.weather().day work, you'd have to return this from the .weather() method. 要使this.weather().day正常工作,您必须从.weather()方法return this

thisFunction.prototype.weather = function(){

    this.day = "Cloudy";
    return this;

};

thisFunction.prototype.event = function(){

    console.log(this.weather().day);

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM