开发者

Is there a way to "undefine" an instance method to reveal the method defined in a prototype?

开发者 https://www.devze.com 2023-02-15 17:57 出处:网络
I\'m trying to wrap my head around javascript prototypes, and started to wonder if there is a way to remove/undefine an instance method defined on an object, so the method in the prototype would be ca

I'm trying to wrap my head around javascript prototypes, and started to wonder if there is a way to remove/undefine an instance method defined on an object, so the method in the prototype would be called. So in the following

/* javascript */
function Foo () {};
Foo.prototype.myMethod = function() {alert('foo')};

var foo1 = new Foo();
var foo2 = new Foo();

foo1.myMethod = function () {alert('foo changed for instance')};
Foo.prototype.myMethod = function () {alert('foo changed in prototype')};

foo1.myMethod(); // alerts 'foo ch开发者_Go百科anged for instance'
foo2.myMethod(); // alerts 'foo changed in prototype'

Is there a way to remove myMethod from instance foo1, so that calling foo1.myMethod(); would call the method defined in the prototype and alert "foo changed in prototype"?

I guess I'm after something akin to removing a method from singleton class in Ruby, like:

# ruby
class Foo
  def myMethod
    puts "foo"
  end
end

f = Foo.new
f.myMethod # => foo

# make singleton class, re-define myMethod for this instance
def f.myMethod
  puts "bar"
end
f.myMethod # => bar

# remove method from singleton class
class << f
  remove_method :myMethod
end
f.myMethod # => foo

I'm asking out of sheer interest, so bonus points for practical use cases for this..


You can do so with delete:

The delete operator deletes a property of an object, or an element at a specified index in an array.

delete foo1['myMethod'];

It is the only way to remove properties of an object. A practical use case would be to remove entries from a hash table, which is implemented by using an object.


You can delete it

function Foo () {};
Foo.prototype.myMethod = function() {alert('foo')};

var foo1 = new Foo();
var foo2 = new Foo();

foo1.myMethod = function () {alert('foo changed for instance')};
Foo.prototype.myMethod = function () {alert('foo changed in prototype')};

foo1.myMethod(); // alerts 'foo changed for instance'
foo2.myMethod(); // alerts 'foo changed in prototype'


// deleting the unwanted method
delete foo1.myMethod;

foo1.myMethod(); // alerts 'foo changed in prototype'
foo2.myMethod(); // alerts 'foo changed in prototype'
0

精彩评论

暂无评论...
验证码 换一张
取 消