我正在学习javascript,并希望有助于理解代码片段。
从Object.DefineProperties定义,第一个参数是一个对象。 MyObjectConstructor是声明还是对象。使用构造函数,我希望调用 new 使其成为一个对象。
这令我感到困惑。或者我在Javascript函数中读到的是对象,所以我将它视为一个对象,这个属性是添加所有staticProps和instanceProps的地方吗?
var _prototypeProperties = function (child, staticProps, instanceProps) {
if (staticProps){
Object.defineProperties(child, staticProps)
};
if (instanceProps) {
Object.defineProperties(child.prototype, instanceProps);
}
};
function myFunction() {
function MyObjectConstructor(element) {
this.element = element;
this.initialized = false;
}
_prototypeProperties(MyObjectConstructor, {...}, {...});
}
答案 0 :(得分:1)
是的,(构造函数)函数也是javascript中的对象,您可以直接向它们添加属性。
示例代码段中的_prototypeProperties
函数确实将staticProperties
放在构造函数上,以便可以将它们作为MyObjectConstructor.myStaticProperty
进行访问。它还确实在instanceProps
对象上放置了MyObjectConstructor.prototype
(更好:"类属性","原型属性"),实例继承了它们:{ {1}}。最后,您的(new MyObjectConstructor).myPrototypeProperty
确实放了"真实"实例上的(自有)属性,特别是MyObjectConstructor
和(new MyObjectConstructor).element
。
答案 1 :(得分:1)
首先:function
是javascript中的first type object
。这意味着您可以将功能作为价值提供。例如:
function test(){
return function(){
console.log('function');
}
}
test()();
返回函数作为返回对象,可以赋值函数和函数另一种值!
var test = function(i) {
// body...
return i;
}
test('123');
字符串' test'参考一个匿名函数,你可以理解你将一个函数传递给一个字符串。
第二:如果你使用new
通过函数创建一个实例,这个函数将被称为construction function
,通常它用于初始化参数,并且实例将采用构造函数自己的属性或方法和原型来自构造函数的属性或方法。
第三:" __proto__
"的实例属性是指构造函数的原型对象。这就是实例可以使用构造函数中的原型属性或方法的原因。
第四:如果你按new
创建实例,this
将引用实例对象!这样实例就可以使用属性和方法。
来自您的代码:
var _prototypeProperties = function (child, staticProps, instanceProps) {
if (staticProps){
Object.defineProperties(child, staticProps)
};
// the properties from the own construction function , like this :
// this.element = element;
// this.initialized = false;
if (instanceProps) {
Object.defineProperties(child.prototype, instanceProps);
}
};
// the properties from the construction function's prototype object . like this :
// MyObjectConstructor.prototype.name = 'somebody';
// MyObjectConstructor.prototype.getName = function(){
// return this.name;
// }
答案 2 :(得分:1)
在JavaScript中,一旦定义,结果函数的作用相同:
function Hat() { }
var Hat = function() { }
传统上,第一个用于创建对象(通常使用new
),第二个用作常规方法。
new
运算符,在函数前面变得有点奇怪。使用new
运算符将:
this
undefined
的隐式返回。例如:
// first define Hat function
function Hat() { this.color = 'red' }
// calling with `new` implicitly returns a new object bound to the function
new Hat()
// > Hat { color: "red" }
// invoking without `new` implicitly returns `unefined`,
// but `this` points to Hat's parent object.
// If running in the browser, Hat's parent object would be `window`
// so now Window.color is set to "red"
Hat()
//> undefined
Window.color
//> "red"
小心new
,因为将返回新对象而不是任何显式返回。
var color = function() { return "blue" }
color()
//> "blue"
new color()
//> color {}
JavaScript本质上是原型的。 new
运算符既不反映原型也不反映经典继承。尽管许多流行的图书馆使用它,但我尽可能避免使用它。
我建议阅读Crockford对JavaScript原型继承的解释:http://javascript.crockford.com/prototypal.html
它很简洁,但是如果你理解他的10行演示代码就会很好。
与bind
,call
和apply
一起玩,以及不同的范围上下文。在理解了范围界定和原型性质之后,剩下的只是语法。