自分で言うとおり、の機能はオブジェクトです。意志の機能を割り当てることができるプロパティとメソッド::関数は、ちょうどオブジェクトリテラル、配列、または何か他のもののようなJSでオブジェクトです。この場合
var someAnonFunction = function(foo)
{
console.log(this);
console.log(this === someAnonFunction);//will be false most of the time
};
someAnonFunction.x = 123;//assign property
someAnonFunction.y = 312;
someAnonFunction.divide = function()
{
console.log(this === someAnonFunction);//will be true most of the time
return this.x/this.y;//divide properties x & y
};
someAnonFunction.divide();
、で参照される関数オブジェクトは、割り当てられていますdivide
と呼ばれる無名関数への参照です(無名関数への参照は、とにかくダビングされました)。したがって、ここにはプロトタイプの関与はありません。あなた自身そう言うと、断っておく:おそらくこれは、より明確である
console.log(someAnonFunction.toString === Function.prototype.toString);//functions are stringified differently than object literals
console.log(someAnonFunction.hasOwnProperty === Object.prototype.hasOwnProperty);//true
または、::メソッド/プロパティ呼び出しがに解決する方法の簡単な方式ですべてのオブジェクトは、ちょうどこれを試して、バックObject.prototype
にさかのぼることができますJSの値:
[ F.divide ]<=========================================================\ \
F[divide] ===> JS checks instance for property divide | |
/\ || | |
|| || --> property found @instance, return value-------------------------------| |
|| || | |
|| ===========> Function.prototype.divide could not be found, check prototype | |
|| || | |
|| ||--> property found @Function.prototype, return-----------------------| |
|| || | |
|| ==========> Object.prototype.divide: not found check prototype? | |
|| || | |
|| ||--> property found @Object.prototype, return---------------------|_|
|| || |=|
|| =======>prototype is null, return "undefined.divide"~~~~~~~~~~~~~~~|X|
|| \/
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~< TypeError can't read property 'x' of undefined
したがって、あなたは上記のコードはプロトタイプを使用して仕事をしたい場合、あなたは(この場合は、Function.prototype
)種類の試作品を強化する必要がありますことを、次の。実際には"ネイティブ"プロトタイプを変更することが推奨されないことを知っていますか?まだ:両方の場合において
Function.prototype.divide = function (a, b)
{
a = +(a || 0);//coerce to number, use default value
b = +(b || 1) || 1;//division by zeroe is not allowed, default to 1
return a/b;
};
function someFunction()
{
return 'someString';
};
var another = function(a, b)
{
return a + b;
};
someFunction.divide(12, 6);//will return 2
another.divide(12, 4);//3
、名前(someFunction
又はanother
)によって参照される機能オブジェクトは、見つからないdivide
というプロパティ、スキャンされます。しかし、そのようなプロパティが見つかるFunction.prototype
をスキャンします。
そうでない場合、JSはObject.prototype
もチェックし、失敗した場合は最終的にエラーが発生します。
What makes my.class.js so fast?(プロトタイプチェーンとの取引)
Objects and functions in javascript(機能の要約<は=> < =>コンストラクタオブジェクト)
What are the differences between these three patterns of "class" definitions in JavaScript?を:私はしばらく前にこのテーマにSO上で非常に長い答えを掲載しました
Javascript - Dynamically change the contents of a function(変数とプロパティに割り当てられ、コンテキストが変更され、匿名関数に曖昧に触れる)
私はChromeでコードを実行それは言う:Uncaught TypeError:オブジェクト関数(num1、num2){ return num1 + num2; } '分割'方法がありません – andri
これはアーキテクチャ上の問題ではありませんか?実際にはdivideはaddNumの子関数ではありません。むしろ、それらは親クラス/オブジェクトを持ち、変数とプロパティを共有して数学を行うことができますか? –
私はこの行をhttp://doctrina.org/Javascript-Objects-Prototypes.html – testndtv