質問

I am new to OOP JavaScript and just having a play when I am getting a Strict Violation in JSLint for the following

function HeaderNav(){
  this.activateMobile = function () {
     alert('activateMobile');
  }
}

the strict violation is on the line

this.activateMobile = function () {

I need the method activateMobile() to have "this." so it works when

var navigation = new HeaderNav();
navigation.activateMobile();

Thank you

役に立ちましたか?

解決

If you do

this.activateMobile = function () {};

the function is not part of the prototype, which means that a subclass of HeaderNav will not get this function (unless you do an explicit super call). Setting a property directly on this only sets that property for that instance

To add a function to a prototype do:

function HeaderNav() {} 
HeaderNav.prototype.activateMobile = function () {
  alert('activateMobile');
};
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top