简体   繁体   中英

Javascript sub function error

function Person() {
}
Function.prototype.subfuncname = function(name) {
  var old = this[name];
  this[name] = function() {
    console.log('testing');
  }
}   
Person.subfuncname("test");
var pe = new Person();

pe.test('test');

expect get 'testing' but get an error (pe.test is not a function)

Please help

Just correcting your code.

Instead of

this[name]=function(){
   console.log('testing');
}

make it

this.prototype[name]=function(){
   console.log('testing');
}

That'll do the trick.

 function Person(){ } Function.prototype.subfuncname=function(name){ this.prototype[name]=function(){ alert('It works!'); } } Person.subfuncname("test"); var pe=new Person(); pe.test('test'); 

You have to add subfuncname function Person object's prototype. Also subfuncname must be called on the instance.

function Person() {}
Person.prototype.subfuncname = function(name) {
  var old = this[name];
  this[name] = function() {
    console.log('testing');
  };
};
var pe = new Person();
pe.subfuncname("test");
pe.test('test');

The only code you need to get the intended result is:

  function Person() { this.test = function(string) { console.log(string); } } var pe = new Person(); pe.test('testing'); 

If you want the function on the prototype of the Person object you can also do this:

 function Person() { } Person.prototype.test = function(string) { console.log('testing'); } var pe = new Person(); pe.test('test'); 

function Person(){

}

Person.prototype.subfuncname = function (txt) {
   console.log(txt);
    alert(txt);
};

var pe=new Person();
pe.subfuncname("Jason");

Test case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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