How can we create functions like Mathematica does?

EDIT:

Based on the suggestion by Bob Hanlon, this code should be better as it isolates a from the context of the notebook.

D1[f_, x_] := Module[{a}, Limit[(-f + (f /. {x -> (x + a)}))/a, a -> 0]]

I've tried this on a few functions and it seems to return the same as D, but there are probably edge cases I haven't considered.

D1[f_, x_] := Limit[(-f + (f /. {x -> (x + a)}))/a, a -> 0]
D1[x^2, x]
D1[3 x^3 + y^2, x]
D1[3 Sin[2 x] y^2 + 14, x]

$2x$

$9x^2$

$6y^2\cos{2x}$


ClearAll[D1]

D1[f : _Function | _Symbol, x_] := Block[{a}, Limit[(-f[x] + f[x + a])/a, a -> 0]]

D1[f_, x_] := D1[Function[x, f], x]

Now these all return 2 x:

D1[x^2, x]

D1[#^2 &, x]

fun[z_] := z^2; D1[fun, x]

D1[fun[x], x]