Skip to content

Instantly share code, notes, and snippets.

@fogus
Created June 1, 2011 17:58
Show Gist options
  • Save fogus/1002886 to your computer and use it in GitHub Desktop.
Save fogus/1002886 to your computer and use it in GitHub Desktop.
mvf.js
var M = function() { this.m = function() { return 42 } };
var inst = new M();
inst.f = function() { return 42 };
// How to tell that f is a function in a field and
// m is a method in an *arbitrary* object?
//
// example:
is_method(inst.f);
//=> false
is_method(inst.m);
//=> true
// Is it possible to write is_method?
@founddrama
Copy link

In your example, the method assignments are functionally equivalent -- this in the constructor is going to be == your inst; the interpreter doesn't keep track of ("doesn't care") whether the value at a given field is assigned as part of the constructor's operation, or if it's assigned later. So the short answer is: "No, you can't write an is_method."

What you're looking for is probably something more like this:

var M = function() { this.v = 42; };
M.prototype.m = function() { return this.v; };

var inst = new M();

inst.f = function() { return this.v; };

inst.hasOwnProperty('f');
// true

inst.hasOwnProperty('m');
// false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment