在prototype属性内部或外部声明变量是否更好?

时间:2015-05-10 12:18:40

标签: javascript class prototype instance-variables

以下哪种情况对性能或适当的技术更好?

案例#1

SELECT 
wp_posts.ID as ID, 
wp_posts.post_title as post_title,
s1.name as main_category,
s1.term_id as main_category_id,
s2.name as main_category,
s2.term_id as main_category_id
FROM 
wp_posts, wp_term_relationships, wp_terms s1, wp_term_taxonomy
LEFT JOIN wp_terms s2
ON s1.term_id = s2.id
WHERE
wp_term_relationships.object_id = wp_posts.ID
AND wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id 
AND wp_term_taxonomy.term_id = s1.term_id
AND wp_term_taxonomy.parent = '0'
AND wp_posts.post_type = 'goods' 
AND wp_posts.post_status = 'publish'
ORDER BY s1.term_id ASC

案例#2

function SomeClass ()
{
    this.someVar = null;
    this.someFunc = function () {}
}

3 个答案:

答案 0 :(得分:2)

这完全取决于您是否希望它们在通过该构造函数创建的实例之间共享。如果你这样做,把它们放在原型上。如果你没有,请在构造函数中设置它们。

请注意,在原型上放置对象/数组的引用可能会让你失望,因为(再次)所有实例都将共享这些引用。

在原型上放置方法(对函数的引用)是相当标准的做法。

这是一个通过在原型上放置数组来绊倒的例子:



function MyConstructor() {
};
MyConstructor.prototype.theArray = []; // Don't do this unless you're really sure

var a = new MyConstructor();
a.theArray.push("foo");
snippet.log(a.theArray.length); // 1 -- so far, everything seems fine

var b = new MyConstructor();
b.theArray.push("bar");
snippet.log(b.theArray.length); // 2 -- huh?!?!

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;

当然,原因是ab都使用相同的数组:原型上的那个。

答案 1 :(得分:1)

如果它们在SomeClass的所有实例之间共享,最好在原型中声明它,因为它们将共享相同的引用,从而减少内存量。

但是如果这些属性因实例而异,则必须在构造函数中声明它。

<强>示例:

function SomeClass () {}
SomeClass.prototype.someVar = null;
SomeClass.prototype.someFunc = function () {}

var a = new SomeClass();
var b = new SomeClass();
a.someFunc === b.someFunc //true because they share the same reference
构造函数中的

function SomeClass ()
{
    this.someVar = null;
    this.someFunc = function () {}
}

var a = new SomeClass();
var b = new SomeClass();
a.someFunc === b.someFunc //false because the now have difference reference

答案 2 :(得分:0)

我认为第一个会更快

function SomeClass ()
{
    this.someVar = null;
    this.someFunc = function () {}
}

因为在这种情况下,访问someClassInstace.someFunc时,javascript将无法在someFunc函数的原型中查找。