将属性或函数附加到函数对象上是否有任何问题?

are there any issues with attaching a property or function to a function object

本文关键字:函数 是否 任何 问题 属性 对象      更新时间:2023-09-26

虽然完全有可能将属性或对象附加到函数对象,但我想知道它是否有任何不那么明显的问题?我似乎在网上找不到任何具体的关于这方面的内容。

var f = function(){};
f.blah = function(){};

将属性附加到函数中是Javascript模拟面向对象编程的核心。

类由函数对象表示,附加在函数对象上的属性规定了方法、成员和继承。

例如:

Class Animal:
    def moves:
        print("moves")
    def calls:
        print("calls")
Class Bird < Animal:
    def moves:
        print("flies")
Class Ostrich < Bird:
    def moves:
        print("runs")
    def calls:
        print("HONK")

在Javascript中是这样表示的:

var Animal = function() { console.log("Animal constructor"); }
Animal.prototype.moves = function() { console.log("moves"); }
Animal.prototype.calls = function() { console.log("calls"); }
var Bird = function() { Animal.call(this); console.log("Bird constructor"); }
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.moves = function() { console.log("flies"); }
var Ostrich = function() { Bird.call(this); console.log("Ostrich constructor"); }
Ostrich.prototype = Object.create(Bird.prototype);
Ostrich.prototype.moves = function() { console.log("runs"); }
Ostrich.prototype.calls = function() { console.log("HONK"); }

有关更多信息,请查看:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript